js实现继承的几种方式

it2026-01-04  10

1.call(),apply()方法实现继承

 call方法的第一个参数的值赋值给类(即方法)中出现的this call方法的第二个参数开始依次赋值给类(即方法)所接受的参数

 apply方法的第一个参数和call相同,第二个参数为数组类型,这个数组中的每个元素依次赋值给类(即方法)所接受的参数

function animal(username){ this.username = username; this.sayHello = function(){ alert(this.username); } } function dog(username,password){ animal.call(this,username); this.password = password; this.sayPassword = function(){ alert(this.password); } } var child = new dog("lisi","123456"); child.sayHello(); child.sayPassword();

上面代码就是用call来实现继承,由于call有能改变this的特点,所以可以来实现继承。而apply实现继承几乎和call是相似的,代码如下:

function animal(username){ this.username = username; this.sayHello = function(){ alert(this.username); } } function dog(username,password){ animal.apply(this,new Array(username)); this.password = password; this.sayPassword = function(){ alert(this.password); } } var child = new dog("lisi","123456"); child.sayHello(); child.sayPassword();

下面我们来介绍第二种实现继承的方式,利用原型链(prototype)来实现继承。

function animal(){ } animal.prototype.hello = "lisi"; animal.prototype.sayHello = function(){ alert(this.hello); } function dog(){ } dog.prototype = new animal();      dog.prototype.constructor = dog; dog.prototype.password = "123456"; dog.prototype.sayPassword = function(){ alert(this.password); } var c = new dog(); c.sayHello(); c.sayPassword();

我们可以看到在dog方法里面,我们在dog.prototype下new了一个animal,目的是将animal中将所有通过prototype追加的属性和方法都追加到dog,从而实现了继承.

dog.prototype.constructor = dog;这句话是因为之前new了一下dog的constructor指向了animal,只要从新覆盖即可。

最后一种实现继承的方法对象冒充(不常用):

function animal(username){ this.username = username; this.sayHello = function(){ alert(this.username); } } function dog(username,password){ this.extend = animal; this.extend(username); delete this.metend; this.password = password; this.sayPassword = function(){ alert(this.password); } } var dog = new dog("lisi","123456"); dog.sayHello(); dog.sayPassword();

这种方法叫做对象冒充。实现原理:让父类的构造函数成为子类的方法,然后调用该子类的方法,通过this关键字给所有的属性和方法赋值。值得注意的是extend是一个自定义临时属性,在执行完函数一定要立即删除。

this.extend是作为一个临时的属性,并且指向animal所指向的对象,执行this.extend方法,即执行animal所指向的对象函数销毁this.extend属性,即此时dog就已经拥有了animal的所有属性和方法

转载于:https://www.cnblogs.com/jcscript/p/5641728.html

最新回复(0)