<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又能正常输出。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
test.eat失败,是因为test的原型链上并没有eat方法,也就是说采用构造函数继承的方法,并不会继承被继承构造函数的原型链。
而test.age能正常输出,是因为使用“apply方法”静态绑定了this对象为Student构造出的对象test,所以test具有age属性。
标准的构造函数继承可以这样写:
eat方法并没有被继承。
因为你 Student 没有继承 People,单单通过 apply 方法是不能继承 People 的,要加一句话,
这样改就行,你上面就一句
People.apply(obj, arguments);只是相当于调用了一下this.age = 22并没有实现继承。需要区分一下,函数变量,函数的执行 和 函数的实例化。
函数在 new 时,会创建实例,原型被继承。