方法和属性从一个类传递到另外一个类的过程app
funtion Person(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
Person.prototype.sayHi = function() {
return "Hi" + this.firstName + " " + this.lastName;
}
function Student(firstName, lastName){
return Person.apply(this, arguments);
}
Student.prototype.sayHi = function(){
return "Hi " + this.firstName + " " + this.lastName;
}
复制代码
咱们真的须要在学生身上从新定义sayHi吗?这彷佛重复…… 那怎么办?函数
function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.sayHi = function(){
return "Hi " + this.firstName + " " + this.lastName;
}
复制代码
将一个对象的原型属性指定为另外一个对象的原型属性!优化
function Student(firstName, lastName){
return Person.apply(this, arguments);
}
Student.prototype = Person.prototype;
var s1 = new Student('李','哈')
s1.sayHi() // "Hi 李 哈"
复制代码
有用:)!ui
继续看看 在Student prototype对象上添加一些别的this
Student.prototype.status = function(){
return 'I am currently a student'
}
复制代码
让咱们用Person建立一个对象spa
var p1 = new Person('下','啦')
p1.status() // 'I am currently a student'
复制代码
哦哦……为何Person原型有student原型的属性?学生继承的是人,而不是人。prototype
问题code
一个更好的选择Object.create对象
建立一个全新的函数并接受它的第一个参数,即新建立对象的原型对象。继承
function Student(firstName, lastName){
return Person.apply(this, arguments);
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.status = function(){
return "I am currently a student!"
}
var p1 = new Person('李', '哈');
p1.status; // undefined
复制代码
Student.prototype 不会影响 Person.prototype !
思考为何不是new?
function Student(firstName, lastName){
return Person.apply(this, arguments);
}
Student.prototype = new Person();
// 1. Person被执行了两次
// 2. 代码重复,增长了多余的不须要的属性在Student的原型对象上面
复制代码
优化一下
function Student(firstName, lastName){
return Person.apply(this, arguments);
}
Student.prototype.sayHi = function(){
return "Hello " + this.firstName + " " + this.lastName;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor; // Person
Student.prototype.constructor = Student;
复制代码
继承的两个要点