在 JavaScript 中,通过组合实现 继承 的优化,也就是借助 原型 可以基于已有的 对象 来创建对象从而实现 继承。
function Object1(attr1, attr2) {
this.attr1 = attr1;
this.attr2 = attr2;
}
function Object2(attr1, attr2, attr3) {
Object1.call(this, attr1, attr2);
this.attr3 = attr3
}
Object2.prototype = Object.create(Object1.prototype);
Object2.prototype.constructor = Object1;
借助原型可以基于已有的对象来创建对象。
通过组合实现继承
<!DOCTYPE html>
<html>
<head>
<title>JavaScript组合实现继承</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
function Person(name, age) {
this.name = name;
this.age = age;
this.setName = function(name){
this.name = name;
}
}
Person.prototype.setAge = function (age) {
this.age = age;
}
function Student(name, age, score){
Person.call(this, name, age);
this.score = score;
this.setScore = function (score) {
this.score = score;
}
}
Student.prototype = Object.create(Person.prototype); //核心代码
Student.prototype.constructor = Student; //核心代码
var s1 = new Student('Tom', 20, 15000);
console.log("s1 instanceof Student: ", s1 instanceof Student, "s1 instanceof Person: ", s1 instanceof Person);
console.log(s1);
console.log(s1.constructor); //Student
</script>
</head>
</html>
程序运行后,控制台输出如下:
借助原型可以基于已有的对象来创建对象,从而实现了继承。
在 JavaScript 中,通过组合实现继承的优化,也就是借助 原型 可以基于已有的对象来创建对象从而实现继承。