原型式继承可以用call()和 Object.create()实现
call()
这个函数允许调用一个在这个文件里别处定义的函数。
- 第一个参数指明了在运行这个函数时想对“this”指定的值,(可以重新指定所调用的函数里所有“this”指向的对象。)
- 其他的变量指明了所有目标函数运行时接受的参数。
call的详细介绍https://blog.csdn.net/qq_41154298/article/details/90693633
Object.create()
Object.create(proto, [propertiesObject])
proto
新创建对象的原型对象。
propertiesObject
可选。如果没有指定为 undefined,则是要添加到新创建对象的可枚举属性(即其自身定义的属性,而不是其原型链上的枚举属性)对象的属性描述符以及相应的属性名称。这些属性对应Object.defineProperties()的第二个参数。
<script>
function Person(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
};
Person.prototype.greeting = function () {
alert('Hi! I\'m ' + this.name.first + '.');
};
function Teacher(first, last, age, gender, interests, subject) {
Person.call(this, first, last, age, gender, interests);
this.subject = subject;
}
Teacher.prototype = Object.create(Person.prototype);
/*使用Object.create()实现方法的继承*/
Teacher.prototype.constructor = Teacher;
/*Teacher()的prototype的constructor属性指向的是Person();
所以我们要改变它让他重新指向Teacher()*/
</script>