Javascript:什么是多级原型层次结构以及为什么我们应该避免它

时间:2012-01-14 02:01:41

标签: javascript coding-style prototype-programming

Google Javascript Coding Guidelines中,它说我们不应该使用多级原型层次结构,因为“这些层次结构比它们最初出现时要难得多!”。实际上我没有明白这意味着什么。我在哪里可以找到一个很好的例子来解释它的用法并说明它的不良影响?

3 个答案:

答案 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.inheritsutil.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 }}。如果链很长,那么属性解析可能是相对较长的操作。

相关问题