JavaScript继承扩展功能 [英] JavaScript inheritance extend function
问题描述
我在Pro JavaScript设计模式的这个函数末尾理解IF子句时遇到了一些麻烦:
I'm having some trouble understanding the IF clause at the end of this function from Pro JavaScript Design Patterns:
function extend(subClass, superClass) {
var F = function() {};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
subClass.superclass = superClass.prototype;
if(superClass.prototype.constructor == Object.prototype.constructor) {
superClass.prototype.constructor = superClass;
}
}
本书解释说这些行确保了超类的构造函数即使超类是Object类本身,也正确设置了属性。然而,如果我省略这三行并执行以下操作:
The book explains that these lines ensure that the superclass's constructor attribute is correctly set, even if the superclass is the Object class itself. Yet, if I omit those three lines and do the following:
function SubClass() {};
extend(SubClass, Object);
alert(Object.prototype.constructor == Object);
警告说'true',这意味着即使没有最后三行,超类的构造函数也能正确设置。那么,在什么条件下,这个IF语句是否有用呢?
The alert says 'true', which means the superclass's constructor is set correctly even without those last three lines. Under what conditions, then, does this IF statement do something useful?
谢谢。
推荐答案
这两行试图避免的问题通常是在替换构造函数的 prototype
属性时产生的,例如:
The problem that those two lines try to avoid, is generally produced when you replace the prototype
property of a Constructor Function, for example:
function Foo () {};
Foo.prototype = {
bar: 'baz'
};
var foo = new Foo();
foo.constructor === Object; // true, but `constructor` should refer to Foo
当创建函数对象,初始化 prototype
属性一个新对象,它包含一个引用函数本身的构造函数
属性,例如:
When functions objects are created, the prototype
property is initialized with a new object, which contains a constructor
property that refers to the function itself, e.g.:
function Bar () {};
var bar = new Bar();
bar.constructor === Bar; // true
当您更换原型
具有另一个对象的属性,此对象具有自己的构造函数
属性,通常从其他构造函数继承,或者从 Object.prototype
继承。 。
When you replace the prototype
property with another object, this object has it's own constructor
property, generally inherited from other constructor, or from Object.prototype
.
var newObj = {};
newObj.constructor === Object;
推荐文章:
- Constructors considered mildly confusing
- JavaScript Prototypal Inheritance
这篇关于JavaScript继承扩展功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!