[Object]继承(经典版)(1)对象冒充和Call
[Object]继承(经典版)(一)对象冒充和Call
作者:zccst
先臆想一下这种方法
一、对象冒充
//结论:Student类只继承了Person类的特权属性和方法,并没有继承Person类的共有属性和方法。
二、call和apply(借用构造函数)
//结论:同前面的对象冒充一样,Student类只继承了Person类的特权属性和方法,并没有继承Person类的共有属性和方法。
作者:zccst
先臆想一下这种方法
var a = function(){ alert(1); } console.log(a); a.m1 = function(){ alert(2); } console.log(typeof a); console.log(typeof a.m1); a.m1(); //结论:给函数绑定一个属性,该属性指向另一个函数
一、对象冒充
//对象冒充,是指将父类的属性和方法一起传给子类作为特权属性和特权方法 function Person(name,age){ this.name = name; this.age = age; this.sayHi = function(){ alert('hi'); } } Person.prototype.walk = function(){ alert('walk.......'); } function Student(name,age,grade){ //是指将父类的属性和方法一起传给子类作为特权属性和特权方法。 this.newMethod = Person; this.newMethod(name,age); delete this.newMethod;//如果不删除,newMethod还有Person的prototype方法walk this.grade = grade; } var s1 = new Student('xiaoming',10,3); console.log(s1);//s1作为Student的对象,拥有父类和子类的属性 //Student { name="xiaoming", age=10, grade=3, sayHi=function() } //s1.walk();//报错 s1.walk is not a function
//结论:Student类只继承了Person类的特权属性和方法,并没有继承Person类的共有属性和方法。
二、call和apply(借用构造函数)
//使用call或apply改变对象的作用域来实现继承,让父类的this等于新创建的子类的对象 function Person(name,age){ this.name = name; this.age = age; this.sayHi = function(){ alert('hi'); } } Person.prototype.walk = function(){ alert('walk.......'); } function Student(name,age,grade){ //让父类的this等于新创建的子类的对象 Person.call(this, name, age); this.grade = grade; } var s1 = new Student('xiaoming',10,3); console.log(s1);//s1作为Student的对象,拥有父类和子类的属性 //Student { name="xiaoming", age=10, grade=3, sayHi=function() } //s1.walk();//s1.walk is not a function
//结论:同前面的对象冒充一样,Student类只继承了Person类的特权属性和方法,并没有继承Person类的共有属性和方法。