原型式继承
原型式继承就是对象继承自其原型对象
在对象的原型对象中添加属性,该对象就会自动继承得到
方式:
一:动态向原型对象中添加
<script>
function Student(name) {
this.name = name;
}
var stu = new Student("tom");
//原型式继承
//方式1:动态向原型对象中添加属性
Student.prototype.age = 21;
Student.prototype.sex = "male";
Student.prototype.run = function () {
console.log(this.name + "正在奔跑!");
};
console.log(stu.age);
console.log(stu.sex);
stu.run();
</script>
二:直接覆盖原型对象
覆盖原型对象实现继承时,一定要给新对象添加一个constructor属性,以便模拟对象的类型
<script>
function Student(name) {
this.name = name;
}
var stu = new Student("tom");
//新增的属性对覆盖之后创建的对象有效
Student.prototype = {
constructor: Student, //如果希望覆盖之后创建的对象是类型相关的,必须添加constructor属性
hobby: "吃饭",
study: function () {
console.log(this.name + "正在学习!");
},
show: function () {
console.log("我叫" + this.name);
}
};
var stu2 = new Student("alice");
console.log(stu.name + "," + stu.hobby); //覆盖之前创建的对象无法访问hobby
console.log(stu2.name + "," + stu2.hobby);
</script>