jquery类继承

use*_*196 23 oop jquery

var A=function(){
};

$.extend(A.prototype, {
    init:function(){
        alert('A init');
    }
});
var B=function(){

};

$.extend(B.prototype,A.prototype,{
    init:function(){
        alert('B init');
    }
});
var p=new A();
p.init();
var x=new B();
x.init();
Run Code Online (Sandbox Code Playgroud)

上面是在jQuery中创建类和继承的最佳方法吗?在B的init中如何调用父的init(类似于OO语言中的super.init())?

Nos*_*dna 20

对于OO,最好在jQuery之外查看.jQuery基于选择器返回的集合.

如果你想要类,有些选择和Base2,JooseJS.Class.

  • 这是一个公认的答案?问:"这是在jQuery中执行X的最佳方式吗?" 答:"不要使用jQuery." 对于我们中的一些人来说,这不是一个真正的选择. (13认同)
  • @umassthrower回答者并不是说他不应该使用jQuery,他建议jQuery不提供类的解决方案.提到的任何选项都可以与jQuery共存. (10认同)

dsp*_*elf 18

John Resig在这里创建了一个简单继承的片段. http://ejohn.org/blog/simple-javascript-inheritance/

他将超类存储到_super变量中,因此您可以像这样调用它

this._super();
Run Code Online (Sandbox Code Playgroud)

你可以参考他的代码片段,以更好地了解他的另一个有用的帖子:http: //alexsexton.com/?p = 51


Dmi*_*kiy 5

如何调用父方法:

var B=function(){
    A.call(this);
};

$.extend(B.prototype,A.prototype,{
        init:function(){
                A.prototype.init.call(this);
                alert('B init');
        }
});
Run Code Online (Sandbox Code Playgroud)


Mat*_*wne 5

如果您不想依赖任何其他库,则可以执行以下操作:

function A() {}
A.prototype.foo = function() {};

function B() {
    A.call(this);
    //Or, if there are arguments that need to be passed to A(),
    //this might be preferable:
    //A.apply(this, arguments);
}

B.prototype = new A();

//Or, if the browser supports ECMAScript 5 and/or you have a shim for Object.create,
//it would be better to do this:
B.prototype = Object.create(A.prototype);

$.extend(B.prototype, {
   //set the constructor property back to B, otherwise it would be set to A
   constructor: B,
   bar: function() {}
});
Run Code Online (Sandbox Code Playgroud)

确保在构造函数中定义任何属性,而不是在原型上定义,例如:

function A() {
    this.baz = null;
}
Run Code Online (Sandbox Code Playgroud)

这避免了无意中共享的原型属性.

有一些库使原型继承更容易:

笔记:

  • 每次替换原型(包括扩展)时,最好将其构造函数属性设置回正确的构造函数.这就是我们将B.prototype.constructor设置为B的原因.如果你要替换A.prototype,你应该这样做:

...

A.prototype = {
    constructor: A,
    foo: function() {}
    //other methods...
}
Run Code Online (Sandbox Code Playgroud)
  • B.prototype = Object.create(A.prototype)优于B.prototype = new A()因为它可以帮助你检测到它的早期,如果你忘了从B()的构造函数中调用A(); 它还允许A()具有所需的参数.旧版浏览器需要垫片; 最简单的填充程序(虽然它不支持完整的Object.create规范)位于本页底部:http://javascript.crockford.com/prototypal.html.