javascript - 构造函数继承的一个问题

查看:87
本文介绍了javascript - 构造函数继承的一个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<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又能正常输出。

解决方案

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); // 动物

这篇关于javascript - 构造函数继承的一个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆