functionPerson(name){ this.name = name; this.say = function(){ alert('My name is '+this.name); } } functionF2E(name,id){ this.temp = Person; this.temp(name); deletethis.temp; this.id = id; this.showId = function(){ alert('Good morning,Sir,My work number is '+this.id); } } var simon = new F2E('Simon',9527); simon.say(); // ‘My name is Simon' simon.showId(); // ‘Good morning,Sir,My work number is 9527’
2.call/apply方式 实质上是改变了this指针的指向
functionPerson(name){ this.name = name; this.say = function(){ alert('My name is '+this.name); } } functionF2E(name,id){ Person.call(this,name); //apply方式改成Person.apply(this,new Array(name)); this.id = id; this.showId = function(){ alert('Good morning,Sir,My work number is '+this.id); } } var simon = new F2E('Simon',9527); simon.say(); // ‘My name is Simon' simon.showId(); // ‘Good morning,Sir,My work number is 9527’
F2E.prototype = new Person(); //此处注意一个细节,showId不能写在F2E.prototype = new Person();前面 F2E.prototype.showId = function(){ alert('Good morning,Sir,My work number is '+this.id); }
var simon = new F2E("Simon",9527); simon.say(); // ‘My name is Simon' simon.showId(); // ‘Good morning,Sir,My work number is 9527’