构造函数继承的一个问题

<html>
<head>
  <title>无标题文档</title>
</head>
<body>
</body>
</html>
<script>
  function People() {
    this.age = 23;
  }
  People.prototype = {
    eat: function () {
      alert('123');
    }
  };
  function Student(name, skin) {
    People.apply(this, arguments);
  }
  var test = new Student('张三', '黄皮肤');
  console.log(test.age);
  test.eat();
</script>

为什么test.eat()方法会有错误,但是test.age又能正常输出。

阅读 3k
5 个回答

test.eat失败,是因为test的原型链上并没有eat方法,也就是说采用构造函数继承的方法,并不会继承被继承构造函数的原型链。

而test.age能正常输出,是因为使用“apply方法”静态绑定了this对象为Student构造出的对象test,所以test具有age属性。

标准的构造函数继承可以这样写:

function Animal() {
  this.species = "动物";
}

function Cat(name,color) {
 this.name = name;
 this.color = color;
}

function Cat(name,color) {
 Animal.apply(this, arguments);
 this.name = name;
 this.color = color;
}
var cat1 = new Cat("大毛","黄色");
alert(cat1.species); // 动物

eat方法并没有被继承。

因为你 Student 没有继承 People,单单通过 apply 方法是不能继承 People 的,要加一句话,

Student.prototype = new People();
function Student(name, skin) {
    var obj = Object.create(People.prototype);
    People.apply(obj, arguments);
    return obj;
}

这样改就行,你上面就一句People.apply(obj, arguments);只是相当于调用了一下this.age = 22并没有实现继承。

需要区分一下,函数变量,函数的执行 和 函数的实例化。

People = function(){
   this.age = 23;
}
People(); //函数执行

People.apply(this,arguments); // 执行的this 指向被改变。 本质还是函数执行。

函数在 new 时,会创建实例,原型被继承。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题