简体   繁体   English

没有原型的Java继承

[英]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();
  1. The 2 commented lines, are they different? 2条评论线是否不同?
  2. 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; 
  3. Quick question added - If 'b' is inheriting from 'a' using b.prototype = Object.create(a.prototype), then would instances of b not be able to call any method of a which is not defined on a's prototype? 添加了快速问题-如果'b'是使用b.prototype = Object.create(a.prototype)从'a'继承的,那么b的实例将无法调用a的原型中未定义的a的任何方法? Please refer - jsfiddle.net/sf4oaxun/3 请参考-jsfiddle.net/sf4oaxun/3

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();

DEMO DEMO

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM