JavaScript object sub-class

纵然是瞬间 提交于 2019-12-03 07:56:42

问题


I want to create sub-class B that inherits from super-class A. my code here:

function A(){
    this.x = 1;
}

B.prototype = new A;
function B(){
    A.call(this);
    this.y = 2;
}
b = new B;
Console.log(b.x + " " + b.y );

when run it,it show B is undefined.


回答1:


You must define the B constructor function before trying to access its prototype:

function A(){
  this.x = 1;
}

function B(){
  A.call(this);
  this.y = 2;
}

B.prototype = new A;

b = new B;
console.log(b.x + " " + b.y );  // outputs "1 2"



回答2:


B.prototype = new A;
function B(){
    A.call(this);
    this.y = 2;
}

should be

function B(){
    A.call(this);
    this.y = 2;
}
B.prototype = new A;



回答3:


Lynda.com advises that you next reassign the constructor to B, as follows.

function B() {
   A.call(this);
   this.y = 2;
}

B.prototype = new A;
B.prototype.constructor = B;



回答4:


In standard class derivation, there is the nearly universal mistake of deriving from a newly created base class instance (B.prototype = new A). The base class constructor at the very least executes unnecessary code and at the worst may crash without the input arguments that shouldn't have to be artificially created just for the sake of derivation. Furthermore, instance functions of the base class instance becomes part of the derived classes prototype, which is appropriate only by sheer luck.

Lets be clear! If you inherit from a base class instance created by the base class constructor (B.prototype = new A) you are not actually directly inheriting from the base class!! You have created an intermediary in the inheritance chain, namely the base class instance!!! Ouch!!!! This is inefficient because there is an extra depth in seeking inherited property values in the inheritance chain. This depth accumulates every time you make this mistake.

So what's the correct way. Instead of B.prototype = new A you should write B.prototype = Object.create(A.prototype). This may not have been available in 09. However in 09 there still was

protoProxy = function(myClass)
{
  function foo(){};
  foo.prototype = myClass.prototype;
  return new foo();
 }

as a substitute for Object.create. Instead of B.prototype = new A you should write B.prototype = protoProxy(A) in 09;



来源:https://stackoverflow.com/questions/1204359/javascript-object-sub-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!