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();
上面是在jQuery中创建类和继承的最佳方法吗?在B的init中如何调用父的init(类似于OO语言中的super.init())?
dsp*_*elf 18
John Resig在这里创建了一个简单继承的片段. http://ejohn.org/blog/simple-javascript-inheritance/
他将超类存储到_super变量中,因此您可以像这样调用它
this._super();
你可以参考他的代码片段,以更好地了解他的另一个有用的帖子:http: //alexsexton.com/?p = 51
如何调用父方法:
var B=function(){
    A.call(this);
};
$.extend(B.prototype,A.prototype,{
        init:function(){
                A.prototype.init.call(this);
                alert('B init');
        }
});
如果您不想依赖任何其他库,则可以执行以下操作:
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() {}
});
确保在构造函数中定义任何属性,而不是在原型上定义,例如:
function A() {
    this.baz = null;
}
这避免了无意中共享的原型属性.
有一些库使原型继承更容易:
笔记:
...
A.prototype = {
    constructor: A,
    foo: function() {}
    //other methods...
}
B.prototype = Object.create(A.prototype)优于B.prototype = new A()因为它可以帮助你检测到它的早期,如果你忘了从B()的构造函数中调用A(); 它还允许A()具有所需的参数.旧版浏览器需要垫片; 最简单的填充程序(虽然它不支持完整的Object.create规范)位于本页底部:http://javascript.crockford.com/prototypal.html.