1.apply,call的實例;
2.用apply,call實現繼承;
前端
// 用apply實例
function Car(brand,color,displacement){
this.brand = brand;
this.color = color;
this.displacement = displacement;
this.info = function(){
return '排量爲'+this.displacement+'的'+this.color+this.brand;
}
}
function person(opt){
Car.call(this,opt.brand,opt.color,opt.displacement);
// Car.apply(this,[opt.brand,opt.color,opt.displacement]);
this.name = opt.name;
this.age = opt.age;
this.say = function(){
console.log('年齡爲'+this.age+'的'+this.name+'買了一輛'+this.info())
}
}
var p = new person({
brand:'benz',
color:'紅色的',
displacement:'3.0',
name:'張三',
age:'25'
})
p.say();
//2.用call,apply實現繼承
function Teacher(name,age){
this.name = name;
this.age = age;
}
function Student(name,age,skill,major){
Teacher.apply(this,[name,age]);
this.skill = skill;
this.major = major
}
var student = new Student('張三',46,'computer','soft')
console.log(student)
複製代碼
熱愛前端,熱愛編程,熱愛分享,歡迎一塊兒聊各類技術問題,一塊兒進步,一塊兒成長!微信:zhan_1337608148
編程