這是JavaScript的古茹問題。我正在嘗試使用更加優雅的JavaScript原型模型。這裏是我的工具代碼(它提供原型的真正的連鎖,並與instanceof運算符正確的工作):我該如何做JavaScript原型繼承(原型鏈)
function Class(conf) {
var init = conf.init || function() {};
delete conf.init;
var parent = conf.parent || function() {};
delete conf.parent;
var F = function() {};
F.prototype = parent.prototype;
var f = new F();
for (var fn in conf) f[fn] = conf[fn];
init.prototype = f;
return init;
};
它讓我做這樣thigns:
var Class_1 = new Class({
init: function (msg) { // constructor
this.msg = msg;
},
method_1: function() {
alert(this.msg + ' in Class_1::method_1');
},
method_2: function() {
alert(this.msg + ' in Class_1::method_2');
}
});
var Class_2 = new Class({
parent: Class_1,
init: function (msg) { // constructor
this.msg = msg;
},
// method_1 will be taken from Class_1
method_2: function() { // this method will overwrite the original one
alert(this.msg + ' in Class_2::method_2');
},
method_3: function() { // just new method
alert(this.msg + ' in Class_2::method_3');
}
});
var c1 = new Class_1('msg');
c1.method_1(); // msg in Class_1::method_1
c1.method_2(); // msg in Class_1::method_2
var c2 = new Class_2('msg');
c2.method_1(); // msg in Class_1::method_1
c2.method_2(); // msg in Class_2::method_2
c2.method_3(); // msg in Class_2::method_3
alert('c1 < Class_1 - ' + (c1 instanceof Class_1 ? 'true' : 'false')); // true
alert('c1 < Class_2 - ' + (c1 instanceof Class_2 ? 'true' : 'false')); // false
alert('c2 < Class_1 - ' + (c2 instanceof Class_1 ? 'true' : 'false')); // true
alert('c2 < Class_2 - ' + (c2 instanceof Class_2 ? 'true' : 'false')); // true
我的問題是:是否有更簡單的方法來做到這一點?
http://codereview.stackexchange.com/ – 2012-08-02 04:23:16
[John Resig](http://ejohn.org/blog/simple-javascript-inheritance/)有一個非常好的類繼承例子。它提供超級和其他好吃的東西。 – elclanrs 2012-08-02 04:26:11
這可能是有趣的:http://ejohn.org/apps/learn/ – 2012-08-02 04:58:19