js实现继承的几种方式
2016-07-04 21:11
881 查看
1.call(),apply()方法实现继承
call方法的第一个参数的值赋值给类(即方法)中出现的thiscall方法的第二个参数开始依次赋值给类(即方法)所接受的参数
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的所有属性和方法
相关文章推荐
- javascript深入理解js闭包
- JSONP实例
- js移除数组中的元素
- Javascript 基本-1
- JavaScript函数调用
- JavaScript网页编程之------数组相关知识
- cropper.js 实现HTML5 裁剪图片并上传(裁剪上传头像。)
- 用js打印直角三角形杨辉三角
- Andriod项目开发实战(2)——JSON和XML的区别
- Javascript之跨浏览器的事件处理程序
- AJAX跨域parsererror报错
- js制作一个简单的div弹窗:
- 前端面试-难点问题2-java和javascript的区别
- JavaScript的大概API
- js回调函数
- JS 处理json 对象或json串
- JSON.stringify()中文乱码
- 转UTF-8为字符串、中文字符串
- js数组求和
- js split() 截取函数