我有Java编程背景,最近一直在尝试使用JavaScript继承。我开始编写一些对象,并阅读了一些示例后,找到了适合我的代码风格。
以下是我的代码:
var Class = function() {};
Class.extend = function(p_constructor) {
var Superclass = this;
// the following line confuses me
p_constructor.prototype = Object.create(Superclass.prototype);
p_constructor.prototype.constructor = p_constructor;
p_constructor.extend = Superclass.extend;
return p_constructor;
};
所以现在,当我想定义一个扩展Class的对象时,我只需要输入:
var Person = Class.extend(function(p_firstName, p_lastName) {
this.firstName = p_firstName;
this.lastName = p_lastName;
});
以下内容将成立:
var p = new Person('john', 'smith');
p instanceof Person; // true
p instanceof Class; // true
我只是不太明白在Class.extend
函数中以下行之间的有效区别:
/* 1) */ p_constructor.prototype = new Superclass();
/* 2) */ p_constructor.prototype = Superclass.prototype;
/* 3) */ p_constructor.prototype = Object.create(Superclass.prototype);
/* 4) */ p_constructor.prototype = Object.create(Superclass);
我知道如果一些超级构造函数抛出错误,使用第一行并不是很明智,但第2、3和4行之间的区别是什么?
this.superclass.apply(this, arguments);
- 然后,如果超级构造函数执行了this.sumthin = ...
,该值将附加到子类实例。 - dalgardsubclass.prototype.super = superclass.prototype
(可能还加上subclass.super = superclass
)。也许你会有兴趣看看我的解决方案(请参见评论中的示例)。 - dalgard