方法和屬性從一個類傳遞到另外一個類的過程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;
複製代碼
繼承的兩個要點