下面再来说缺点:
缺点显而易见,原型链方式继承,就是实例化子类时不能将参数传给父类,也就是为什么这个例子中function Person()没有参数,而是直接写成了this.name=”Simon”的原因。下面的代码将不能达到预期的效果:
复制代码 代码如下:
function Person(name){
this.name = name;
}
Person.prototype.say = function(){
alert('My name is '+this.name);
}
function F2E(name,id){
this.id = id;
this.showId = function(){
alert('Good morning,Sir,My work number is '+this.id);
}
}
F2E.prototype = new Person();
var simon = new F2E("Simon",9527);
simon.say();
simon.showId();
function Person(name){
this.name = name;
}
Person.prototype.say = function(){
alert('My name is '+this.name);
}
function F2E(name,id){
this.id = id;
this.showId = function(){
alert('Good morning,Sir,My work number is '+this.id);
}
}
F2E.prototype = new Person(); //此处无法进行传值,this.name或者name都不行,直接写F2E.prototype = new Person('wood')是可以的,但是这样的话simon.say()就变成了My name is wood
var simon = new F2E("Simon",9527);
simon.say(); //弹出 My name is undefined
simon.showId();
最后,总结一下自认为较好的继承实现方式,成员变量采用对象冒充方式,成员方法采用原型链方式,代码如下:
复制代码 代码如下:
function Person(name){
this.name = name;
}
Person.prototype.say = function(){
alert('My name is '+this.name);
}
function F2E(name,id){
Person.call(this,name);
this.id = id;
}
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();
simon.showId();
您可能感兴趣的文章: