[英]Javascript inheritence without prototype
Please refer - http://jsfiddle.net/sf4oaxun/ 请参考-http://jsfiddle.net/sf4oaxun/
function a() {
this.say = function () {
alert("hello");
};
}
a.prototype.what = function () {
alert("234234");
};
function b() {}
//b.prototype = Object.create(a);
//b.prototype = a;
var b1 = new b();
b1.say();
Why does say not get invoked, and errors out when using either of the commented lines(please uncomment it) 为什么说不被调用,并且在使用任何一条注释行时都会出错(请取消注释)
b.prototype = Object.create(a); b.prototype = a;
say
is only available within the function a's constructor. say
仅在函数a的构造函数中可用。 It will not be inherited. 它不会被继承。
so that's the reason why b1.say() was not available. 所以这就是为什么b1.say()不可用的原因。
Another thing, both the statements are wrong. 另一件事,两个陈述都是错误的。
It should be either 应该是
b.prototype = Object.create(a.prototype)
so that what
property will be inherited by b. 这样b将继承
what
属性。
Another way of doing is 另一种方法是
b.prototype = a.prototype
But in this case, any changes to b.prototype
will affect a.prototype
但是在这种情况下,对
b.prototype
任何更改都会影响a.prototype
In case if you want to inherit the constructor properties as well, then 如果您还想继承构造函数的属性,那么
b.prototype = new a();
When you use Object.create the prototype is curried over, but your constructor is never run. 当您使用Object.create时,原型会被重写,但是您的构造函数永远不会运行。 This the code inside the original A "class" isn't actially executing.
原始A“类”中的代码实际上并没有执行。 To get b1 to have both say and what, you would do
要让b1拥有发言权和发言权,您可以
b.prototype = new a();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.