js中实现继承的几种方法

来源:互联网 发布:阿里云cdn 使用 编辑:程序博客网 时间:2024/04/28 21:53

在网上查js的实现继承的方法,众说纷纭,各有各的说法,但是万变不离其宗,总结下来也就是下面这三种方法。

方法1.通过构造函数实现继承
方法2.通过原型链实现继承
方法3.通过call和apply方法实现继承


1:通过构造函数实现继承

function Parent(firstname)  {      this.firstname=firstname;      this.age=23;      this.sayAge=function()      {          console.log(this.age);      }  }  function Child(firstname)  {      this.parent=Parent;      this.parent(firstname); //执行parent所指向的对象函数     delete this.parent; //删除该方法     this.saySomeThing=function()      {          console.log(this.fname);          this.sayAge();      }  }  var mychild=new  Child("李");  mychild.saySomeThing();  

2:通过原型链实现继承

function Person(){};Person.prototype.hello = 'Fuck The World';Person.prototype.say = function(){    alert(this.hello)}function Child(){}Child.prototype = new Person();Child.prototype.world = 'world';Child.prototype.sayWorld = function(){    alert(this.world);}var c = new Child();c.say();c.sayWorld();

3:通过call和apply方法实现继承

首先我们来介绍一下callheapply的用法,其实二者的作用是完全一样的,只是接受参数的方式不太一样。

语法如下:

var func = function(arg1,arg2){};func.call(this,arg1,arg2);func.apply(this,[arg1,arg2]);

我们来举一个最简单的例子:

function fly(){    alert('I can fly');}function run(){    alert('I can run');}fly.call(run);

输出结果是什么?其实结果是‘I can fly’;fly.call(run)就等价于fly();
我了个毛。。。。。。fly()你妹啊,那你直接写fly()就好了啊,还用call()干嘛。

其实说的直白一点,我们可以这样理解,call其实就是一个在中间牵线的,fly会飞,而run只会跑不会飞,但是现在run想飞,而fly却不让他飞,于是run就找来了call,并承诺给call一个漂亮妹子(呃。。。这句省略),于是call就把fly爆了菊并在fly后面加了个点,然后把run抱进了括号里面,于是run就会飞了。

其实总结下来就一句话:call和apply就是把括号里的对象来集成括号外的函数的属性。我们把这种现象叫做继承!!!

到此打住,说多了就晕了。
0 0
原创粉丝点击