2012-01-14 86 views
1

Google Javascript Coding Guidelines,有人说,我们不应该使用多级原型层次,因为“这些层次是更难获得正确的不是他们第一次出现!” 。其实我没有明白它的意思。我在哪里可以找到一个很好的例子来解释其用法并说明其不良影响?的Javascript:什么是多层次的原型层次,为什么我们应该避免

+3

你熟悉原型继承的基础? – 2012-01-14 02:05:34

+0

这是什么原因?一旦你知道如何做对,你就没事。 – 2012-01-14 02:40:56

+0

这并不是说你不应该使用它们。它只是说你应该使用一个库。简短的“不推荐”概要会引起误解,可能是指手动摆弄。 – user123444555621 2012-01-14 03:02:52

回答

0

这是因为原型链解决问题。当你有像foo.bar它并不意味着bar财产直接属于foo对象,因此它开始的foo原型链中寻找bar。如果链条很长,那么属性解析可能是相对较长的操作。

+0

但是,这不符合“得到它的权利”这么多只是一个潜在的性能问题的问题。你能再谈一谈吗? – nnnnnn 2012-01-14 02:30:40

+0

我不认为这是一个性能问题...... – 2012-01-14 02:43:08

+0

这不是任何明智的浏览器的性能问题,原型链高度优化。 – Raynos 2012-01-14 02:50:27

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继承了Dog原型bark方法,和dog2继承了该方法(从Dog原型)和来自rollOver方法原型TrainedDog

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模拟。

相关问题