开发者

Minimalistic prototype (js framework)

I want to use the prototype javascript framework for its "class" and inheritance capabilities. For everything else I will be using jQue开发者_如何学Gory. Is there a minimalist version of prototype that will give me just this functionality? I don't want the additional overhead of the entire library if I won't be using it all.

To be specific I want the class and inheritence capabilities that allow me to define classes as follows (examples from wikipedia):

var FirstClass = Class.create( {
  // The initialize method serves as a constructor
  initialize: function () {
   this.data = "Hello World";
  }
});

and to extend another class:

MyNewClass = Class.create( FirstClass, { 
  //Override the initialize method
  initialize: function() { 
    //..
  }, 
  // ...more methods add ... 
});

Plus I don't want conflicts between the frameworks (i.e. $ should only be used by jQuery..I only want prototype (or any other suggestion would be fine) for class creation / inheritance).


Inheritance.js was the model that the guys developing the Prototype library have been inspired from and I think it is what you where asking for.

Note: $super seems to be this.parent as stated in the comments below.


If you're looking for something minimalistic:

function clone(obj)  {
    if(typeof obj !== 'undefined') {
        clone.prototype = obj;
        return new clone;
    }
}

function copy(dest, src) {
    for(var name in src) {
        if(src.hasOwnProperty(name))
            dest[name] = src[name];
    }
}

function classof(constructor) {
    return {
        extend : function(base) {
            constructor.prototype = clone(base.prototype);
            return this;
        },

        mixin : function(members) {
            copy(constructor.prototype, members);
            return this;
        }
    };
}

Example usage:

// base class:
function Foo(value) {
    this.value = value;
}

classof(Foo).mixin({
    inc : function() { ++this.value; }
});

// derived class:
function Bar() {
    Foo.apply(this, arguments);
}

classof(Bar).extend(Foo).mixin({
    dec : function() { --this.value; }
});

var bar = new Bar(42);
bar.inc();
bar.dec();


Don't mix Prototype and jQuery. My experience says they don't play nice together. My personal preference would be to use Prototype due to the superior syntactical sugar.

There's no way to disable Prototype's $-function. You can disable jQuery's use of $ via jQuery.noConflict() - but it's not perfect.

As @mhtiza said, use Interitance.js for the class-sugar if you decide to stick to jQuery.


For version 1.7.1 I deleted everything below line 1625 in the prototype.js file and I no longer have conflicts with bootstrap and jquery. And the Class.create function still works. The class.create is the only method I wanted as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜