English 中文(简体)
Javascript: 多层次原型等级是什么,为什么我们应当避免。
原标题:Javascript: What are multi-level prototype hierarchies and why we should avoid it

。 谷歌 Java版编码准则说,我们不应使用多级原型等级,因为“这些等级比最初的>更难以获得权利。 实际上,我拿不到这意味着什么。 我能找到一个很好的例子来解释其用法和说明其坏效果?

问题回答

这是两级遗产继承的一个例子:

// 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原型)和<编码>。 http://www.un.org/Depts/DGACM/index_french.htm

我认为,该条指的是不是手工建立原型链,而是使用一个图书馆,如<代码>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 此外,还处理在遗产浏览器中的<代码>目标/代码>。

这是因为原型链分辨率问题。 如您有<代码>foo.bar,则t 系指bar 财产直接属于foo的物体,因此开始在<代码> foo原型链中查询bar。 如果链条很长,那么财产解决就会比较长。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签