在Google Javascript Coding Guidelines中,它说我们不应该使用多级原型层次结构,因为“这些层次结构比它们最初出现时要难得多!”。实际上我没有明白这意味着什么。我在哪里可以找到一个很好的例子来解释它的用法并说明它的不良影响?
答案 0 :(得分:5)
这是两级继承的一个例子:
// 1. level constructor
var Dog = function ( name ) {
this.name = name;
};
Dog.prototype.bark = function () { /* ... */ };
// 2. level constructor
var TrainedDog = function ( name, level ) {
Dog.apply( this, arguments ); // calling the super constructor
this.level = level;
};
// set up two-level inheritance
TrainedDog.prototype = Object.create( Dog.prototype );
TrainedDog.prototype.constructor = TrainedDog;
TrainedDog.prototype.rollOver = function () { /* ... */ };
// instances
var dog1 = new Dog( 'Rex' );
var dog2 = new TrainedDog( 'Rock', 3 );
此处,dog1
继承了bark
原型中的Dog
方法,dog2
继承了该方法(来自Dog
原型)和{来自rollOver
原型的{1}}方法。
答案 1 :(得分:2)
我认为这篇文章指的是不是手动设置原型链而是使用库,例如goog.inherits
或util.inherits
手动你必须做
var Child = function Child() { ... };
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
// for some common value of extend
extend(Child.prototype, {
...
});
这可以简化为
var Child = function Child() { ... };
goog.inherits(Child, Parent);
extend(Child.prototype, {
...
});
请注意,此处goog.inherits
还会处理旧版浏览器中的Object.create
仿真。
答案 2 :(得分:0)
这是因为原型链解析问题。当你有类似foo.bar
之类的内容时,并不意味着bar
属性直接属于foo
对象,因此它开始在{{1}的原型链中搜索bar
}}。如果链很长,那么属性解析可能是相对较长的操作。