javascript中的继承不起作用

时间:2013-10-04 19:16:44

标签: javascript oop prototypal-inheritance

为什么jordan不具有Human类的属性?不应该说Coder.prototype = new Human;足以让所有Coder类继承Human类的所有属性吗?

是否与将函数定义为赋值有关?

var Human = function() {
     var hi = function() {
         alert('hi');
      };
     return {
        name : 'dan',
       sayHi : hi
     };
};

var dan = new Human();

var Coder = function() {
   var code = function() {
      alert('1010101');
   };    
  return {
    code : code
  };
};

Coder.prototype = new Human;
Coder.prototype.constructor = new Coder;
var jordan = new Coder();
console.log(jordan);

2 个答案:

答案 0 :(得分:2)

您的构造函数不会返回它们正在创建的对象,因此继承将不起作用。请改用:

var Human = function() {
     this.sayHi = function() {
         alert('hi');
     };
     this.name = 'dan';
};

var dan = new Human();

var Coder = function() {
   this.code = function() {
      alert('1010101');
   };    
};

Coder.prototype = new Human;
Coder.prototype.constructor = Coder;
var jordan = new Coder();
console.log(jordan);

另一种选择,将内容从Human移动到原型:

var Human = function() {};
Human.prototype.sayHi = function() {
    alert('hi');
};
Human.prototype.name = 'dan'; // will be shadowed if redefined on instances

var Coder = function() {};
Coder.prototype = Object.create(Human.prototype);
Coder.prototype.code = function() {
    alert('1010101');
};  
var jordan = new Coder();
console.log(jordan);

Object.create的填充是available on MDN

答案 1 :(得分:1)

这是一件有趣的事情:JS构造函数可以返回一个成为它的对象。然而,这个对象不遵循为构造函数定义的原型(在这种情况下,它是一个普通的Object)。看起来像你的代码的正确方法是:

var Human = function() {
    var hi = function() {
        alert('hi');
    };
    this.name = "dan";
    this.sayHi = hi;
};

// or even:
var Human = function() {
    this.name = "dan";
};

Human.prototype.sayHi = function() {
    alert('hi');
};

类似于Coder。继承代码没问题。