您好,欢迎访问一九零五行业门户网

javascript原型链继承方式用法和缺点实例详解

原型链方式
function person(){ this.name = 'simon'; } person.prototype.say = function(){ alert('my name is '+this.name); } function f2e(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(9527); simon.say(); simon.showid(); alert(simon.hasownproperty('id')); //检查是否为自身属性
接下来按照上面的例子来理解以下js原型链概念:
原型链可以理解成:js中每个对象均有一个隐藏的__proto__属性,一个实例化对象的__proto__属性指向其类的prototype方法,而这个prototype方法又可以被赋值成另一个实例化对象,这个对象的__proto__又需要指向其类,由此形成一条链,也就是前面代码中的
f2e.prototype = new person()
这句是关键。js对象在读取某个属性时,会先查找自身属性,没有则再去依次查找原型链上对象的属性。也就是说原型链的方法是可以共用的,这样就解决了对象冒充浪费内存的缺点。
下面再来说缺点:
缺点显而易见,原型链方式继承,就是实例化子类时不能将参数传给父类,也就是为什么这个例子中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();
以上就是javascript原型链继承方式用法和缺点实例详解的详细内容。
其它类似信息

推荐信息