函数是特定环境中执行代码的对象,使用apply()和call()方法可以在新创建的对象上执行构造函数,如下
function Box(name,age) { this.name = name; this.age = age; } function Desk(name, age){ Box.call(this, name, age); //this是Desk本身,对象冒充,只能继承构造函数里面的信息,原型里面的无法继承 } var desk = new Desk('Lee', 100); alert(desk.name);//Lee
function Box(name,age) { this.name = name; this.age = age; } Box.prototype.family = '家庭'; function Desk(name, age){ Box.call(this, name, age); //this是Desk本身,对象冒充,只能继承构造函数里面的信息,原型里面的无法继承 } var desk = new Desk('Lee', 100); alert(desk.name);//Lee alert(desk.family);//undefined
function Box(name,age) { this.name = name; this.age = age; this.family = ['哥哥','姐姐','弟弟'];//引用类型放在构造函数不被共享 } Box.prototype.family = '家庭'; function Desk(name, age){ Box.call(this, name, age); //this是Desk本身,对象冒充,只能继承构造函数里面的信息,原型里面的无法继承 } var desk = new Desk('Lee', 100); alert(desk.name);//Lee desk.family.push('妹妹'); alert(desk.family);//哥哥姐姐弟弟妹妹 var desk2 = new Desk('Jack', 200); alert(desk2.family);//哥哥姐姐弟弟
function Box(name,age) { this.name = name; this.age = age; this.family = ['哥哥','姐姐','弟弟'];//引用类型放在构造函数不被共享 } //构造函数里的方法,放在构造里,每次实例化,都会分配一个内存地址,浪费,所以放在原型函数里 Box.prototype.run = function () { return this.name + this.age; }; Box.prototype.family = '家庭'; function Desk(name, age){ Box.call(this, name, age); //this是Desk本身,对象冒充,只能继承构造函数里面的信息,原型里面的无法继承 } var desk = new Desk('Lee', 100); alert(desk.run());//undefined 继承不到prototype中,使用组合继承,如下
//组合继承
function Box(name,age) { this.name = name; this.age = age; this.family = ['哥哥','姐姐','弟弟'];//引用类型放在构造函数不被共享 } //构造函数里的方法,放在构造里,每次实例化,都会分配一个内存地址,浪费,所以放在原型函数里 Box.prototype.run = function () { return this.name + this.age; }; Box.prototype.family = '家庭'; function Desk(name, age){ Box.call(this, name, age); //this是Desk本身,对象冒充,只能继承构造函数里面的信息,原型里面的无法继承 } Desk.prototype = new Box(); //原型链继承 var desk = new Desk('Lee', 100); alert(desk.run());//Lee100