zoukankan      html  css  js  c++  java
  • JS Call()与Apply()

    JS Call()与Apply()

    ECMAScript规范给所有函数都定义了Call()与apply()两个方法,call与apply的第一个参数都是需要调用的函数对象,在函数体内这个参数就是this的值,剩余的参数是需要传递给函数的值,call与apply的不同就是call传的值可以是任意的,而apply传的剩余值必须为数组。

    例如:function add(a, b) { return a + b; }

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

    /*apply用法

    * var a1 = sub.apply(add, [4, 2]);

    *var a2= add.apply(sub, [4, 2]);  

    */

    var a1 = sub.call(add, 4, 2);

    var a2= add.call(sub, 4, 2);

    输出:a1=2  a2=6

    感觉还是有意未尽,更有意思的还在下面

    js总是认为他是万能的,既然高级语言会继承,我js也不能示弱:JS模仿继承

      function fun1() {

                this.a = 123;

            this.add = function () { return  this.a }

            }

            function fun2() {

                this.a = 456;

            }

            var f1=new fun1()

            var f2=new fun2()

            var a = f1.add.call(f2);  // a输出的是456

    这里就是把啊f1的方法拿给f2来使用,f2便可以使用f1中所有的方法,这不正是高级语言中继承的概念喽。当然根据综上可扩展出多继承,使用多个call便可以实现多继承

       function fun1() {

                this.add = function () { return this.a }

            }

            function fun2() {

       

                this.sub = function () { return this.a-this.b }

            }

            function fun3() {

                this.a = 10;

                this.b = 2;

                 fun1.call(this);

                fun2.call(this);

            }

            var f3 = new fun3()

            alert(f3.add());

            alert(f3.sub())

  • 相关阅读:
    UVa532 Dungeon Master 三维迷宫
    6.4.2 走迷宫
    UVA 439 Knight Moves
    UVa784 Maze Exploration
    UVa657 The die is cast
    UVa572 Oil Deposits DFS求连通块
    UVa10562 Undraw the Trees
    UVa839 Not so Mobile
    327
    UVa699 The Falling Leaves
  • 原文地址:https://www.cnblogs.com/leo388/p/4486435.html
Copyright © 2011-2022 走看看