如果我的Object返回错误的构造函数JavaScript,这有关系吗?

时间:2015-04-19 08:56:25

标签: javascript

好的,看看这个问题,看起来似乎很重要,但让我们看看我做过的测试。

所以我创建了3个构造函数。我做了通常的汽车,然后是马自达,然后是MX8构造函数。所有这些都基于JSFiddle中的代码继承。以下是我所做的内容,更多细节可以在JSFiddle.

中找到

顺便说一下,我是Object.create的忠实粉丝,不需要任何保姆。

var Car = function () {
    //code here
}

var Mazda = function (type) {
    this.type = type;
    //more code here including a simple method test    
}

var MX8 = function () {
   //more code here
}

Mazda.prototype = new Car();
MX8.prototype = new Mazda("MX8");

var z = new MX8();

//refer to my JSFiddle
z.interior;               // got correct interior
z.type;                   // got correct type ie model
z.warrantyInfo();         // method was correctly inherited
z.speed;                  // got correct speed
z.constructor === MX8;    // false (unless I specify the constructor in the code of which is commented out in my JSFiddle)

1 个答案:

答案 0 :(得分:1)

简短回答
您需要显式设置构造函数。

function Base() {}
function Derived() {}

// old prototype object is gone, including constructor property
// it will get however all the properties attached by Base constructor
Derived.prototype = new Base(); 

Derived.prototype.constructor = Derived;
  

我的Object返回错误的构造函数是否重要?

嗯,这取决于您是否使用该属性。我会说保持正确的构造函数是一个好习惯。

可能的用例:

function getType (target) {
  // name is empty unless you use the function declaration syntax 
  // (read-only property) 
  return target.constructor.name; 
}

getType(new Derived()) // "Derived"
getType(new Base()) // "Base"

旁注
在JS中有更好的实现继承的方法。 我最喜欢的模式如下:

function Base (x) { this.x = x; }

function Derived (x, y) { Base.call(this, x); this.y = y; }

// creates an empty object whose internal "[[Prototype]]" property 
// points to Base.prototype
Derived.prototype = Object.create(Base.prototype);
Derived.prototype.constructor = Derived;

Object.create背后的标志是基于:

function create (proto) {
  function f () {}
  f.prototype = proto;
  return new f();
}

实际函数Object.create更好,因为您可以将null作为原型传递,但使用上述代码无效。 无论如何,您应该观看这个出色的播放列表:Crockford on JavaScript