gvl*_*sov 5 javascript constructor prototype coding-style prototypal-inheritance
我不是JavaScript的新手,但我从来不能理解它的原型继承.
假设我们有父类和子类"类"(函数Parent和Child创建对象).为了能够创造孩子,我们首先需要
Child.prototype = new Parent();
Run Code Online (Sandbox Code Playgroud)
这就是困难:通过将原型分配给Child,我们得到一个对象Parent,它在我们的代码中没有做任何事情,只是与Children共享它的属性.但仍然会调用Parent的构造函数!例如,如果父代表某个UI对象,那么在我们的应用程序中,我们将有另外一个我们实际上不想创建的对象!当然,这可能会影响我们的申请状态.
我看到了一种方法来处理这个问题:将某些参数传递给Parent构造函数,指示我们创建的对象仅用于原型,而不是一般用途,如:
RedButton.prototype = new Button(FOR_PROTO_ONLY);
Run Code Online (Sandbox Code Playgroud)
然后在Parent构造函数中决定是否执行任何可显示的内容.但这是一个如此丑陋的解决方法!
在面向类的语言中,例如Java,我们根本没有这样的问题,因为继承不会假设调用任何其他函数.我应该怎么做才能在我的程序中使用这种丑陋的技术,并且仍然能够创建一个漂亮的原型层次结构?
您可以做的一件事是将父级的实例分配给构造函数中的原型属性。这意味着您不必创建父级的无关实例,因此可以缓解您提到的问题,您最终可能会定义额外的 GUI 组件。然而,这确实意味着在实例化子实例之前,您必须至少有一个父实例,因此仅此一点就限制了其在非常特定的情况下的有用性。
这是一个例子: http: //jsfiddle.net/xwwWZ/
var Child = function() {
this.throwATantrum = function() {
alert("Waaaaaaaaaah");
}
};
var Parent = function() {
// Set the prototype here to avoid having to create an extra instance elsewhere.
Parent.prototype = this;
this.sayHello = function() {
alert("Hello!");
}
};
// We must, however, instantiate an instance of the parent before we can
// instantiate an instance of a child.
var p = new Parent();
Child.prototype = Parent.prototype;
var c = new Child();
c.throwATantrum();
c.sayHello();
Run Code Online (Sandbox Code Playgroud)