对象冒充
function Person(name,age){ this.name=name; this.setName=function(name){ this.name=name; } this.getName=function(){ return this.name; } this.getInfo=function(){ alert("name:"+this.name); } }; function Student(name,age){ this.method=Person; this.method(name); delete this.method; this.age=age; this.setAge=function(age){ this.age=age; } this.getAge=function(){ return this.age; } this.getInfos=function(){ alert("name:"+this.name+",age:"+this.age); } } var person=new Person("person"); var student=new Student("student",22); person.getInfo(); student.getInfos();
call 方法方式
call 方法是 Function 对象中的方法,因此我们定义的每个函数都拥有该方法。可以通过函数名来调用 call 方法,call 方法的第一个参数会被传递给函数中的 this,从第 2 个参数开始,逐一赋值给函数中的参数。
function Person(name,age){ this.name=name; this.setName=function(name){ this.name=name; } this.getName=function(){ return this.name; } this.getInfo=function(){ alert("name:"+this.name); } }; function Student(name,age){ Person.call(this,name); this.age=age; this.setAge=function(age){ this.age=age; } this.getAge=function(){ return this.age; } this.getInfos=function(){ alert("name:"+this.name+",age:"+this.age); } } var person=new Person("person"); var student=new Student("student",22); person.getInfo(); student.getInfo(); student.getInfos();
apply 方法方式
function Person(name,age){ this.name=name; this.setName=function(name){ this.name=name; } this.getName=function(){ return this.name; } this.getInfo=function(){ alert("name:"+this.name); } }; function Student(name,age){ Person.apply(this,new Array(name)); this.age=age; this.setAge=function(age){ this.age=age; } this.getAge=function(){ return this.age; } this.getInfos=function(){ alert("name:"+this.name+",age:"+this.age); } } var person=new Person("person"); var student=new Student("student",22); person.getInfo(); student.getInfo(); student.getInfos();
原型链方式(无法给构造函数传参数)
function Person(){} Person.prototype.name="name"; Person.prototype.getInfo=function(){ alert("name:"+this.name); } function Student(){} Student.prototype=new Person(); Student.prototype.age=0; Student.prototype.getInfos=function(){ alert("name:"+this.name+",age:"+this.age); } var person=new Person(); person.name="person"; var student=new Student(); student.name="student"; student.age=22; person.getInfo(); student.getInfo(); student.getInfos();
混合方式(推荐)
function Person(name){ this.name=name; } Person.prototype.getInfo=function(){ alert("name:"+this.name); } function Student(name,age){ Person.call(this,name); this.age=age; } Student.prototype=new Person(); Student.prototype.getInfos=function(){ alert("name:"+this.name+",age:"+this.age); } var person=new Person("person"); var student=new Student("student",22); person.getInfo(); student.getInfo(); student.getInfos();