使用JS中的Call方法实现继承和多重继承

call方法:

调用一个对象的一个方法,以另一个对象替换当前对象。

call([thisObj[,arg1[, arg2[, [,.argN]]]]])

thisObj
可选项。将被用作当前对象的对象。
arg1, arg2, , argN
可选项。将被传递方法参数序列。
说明
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。

如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

obj1.method1.call(obj2,argument1,argument2)
如上,call的作用就是把obj1的方法放到obj2上使用,后面的argument1..这些做为参数传入

举例说明1:

  <script type="text/javascript">
    function add(a,b){
	   alert(a+b);
	}

	function sub(a,b){
	   alert(a-b);
	}

	add.call(sub,4,5);
  </script>
输出结果为:9,表示把add方法放到sub上使用,然后传入后面相应的参数


举例说明2:

  <script type="text/javascript">
      function test1(){
	    this.name="test1";
		this.method1=function(){
		   alert(this.name);
		}
	  }
	  function test2(){
	    this.name="test2";
	  }

	  var t1=new test1();
	  var t2=new test2();
      t1.method1.call(t2);
  </script>
输出结果为:test2,表示把t1的method1方法放到t2中去执行


举例说明3:单重继承

  <script type="text/javascript">
      function animal(){
        this.eat=function(){
          alert("动物在吃饭");
        }
      }
      function dog(){
        animal.call(this);
      }

      var d=new dog();
      d.eat();
  </script>

输出:动物在吃饭,animal.call(this);表示把animal对象代替了this对象,那么this对象就有了animal中的属性和方法


举例说明4:多重继承

  <script type="text/javascript">
      function animal(){
        this.eat=function(){
          alert("动物在吃饭");
        }
      }

      function dogClass(){
        this.type="狗类";
      }
      function dog(){
        animal.call(this);
        dogClass.call(this);
      }

      var d=new dog();
      d.eat();
      alert(d.type);
  </script>

输出:动物在吃饭,狗类,同上,同时dogClass对象也代替了this对象,那么dog中也会有dogClass类中的属性和方法,实现了多重继承




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值