zoukankan      html  css  js  c++  java
  • JavaScript函数调用模式

    1、方法调用模式:

    var myObj = {
        value : 0;
        increment:function(inc){
            this.value += typeof inc === 'number' ? inc : 1;
        }
    }
    myObj.increment();
    console.info(myObj.value); // 1        
    

      

    2、函数调用模式:

    当一个函数并非一个对象的属性时,那么它被当做一个函数来使用,这时 this 被绑定到全局对象,要解决这个问题,需要在内部重新命名一个变量。获取内部函数的控制权

    myObj.double = function(){
        var _self = this;
        var helper = function(){
            _self.value = add(_self.value,_self.value);
        }
        helper(); //函数形式调用helper
    };
    myObj.double();
    console.info(myObj.value);
    

      

    3、构造器模式:

    如果在一个函数前面带上new来调用,那么将创建一个隐藏连接到该函数的prototype成研的新对象,同时this将会被绑定到新对象上。

    var Quo = function(str){
        this.status = str;
    }
    Quo.prototype.get_status = function(){
        return this.status;
    }
    //构造一个Quo实例
    var myQuo = new Quo("abc");
    console.info(myQuo.get_status());
    

      

    4、Apply 模式:

    apply方法构建一个参数数组并用其去调用函数,也允许我们选择this值,apply接收两个参数,一个是将被绑定给this的值,另一个是参数数组。

    var arr = [3,4];
    var sum = add.apply(null,arr);
    
    //构造一个包含status成员的对象
    var statusObj = {
        status : "OK"
    };
    //statusObj 并没有继承自Quo.prototype,但可以在statusObj上调用get_status方法,尽管statusObj并没有一个名为get_status的方法。
    var status = Quo.prototype.get_status.apply(statusObj);
    console.info(status);  //"OK"
  • 相关阅读:
    A1061 Dating [字符串比较]
    A1058 A+B in Hogwarts [进制转换]
    A1027 Colors in Mars[简单模拟--进制转换]
    A1031 Hello World for U[图形输出]
    刷PAT的一些思考—Day 1
    A1009 Product of Polynomials[简单模拟--多项式相乘]
    A1002 A+B for Polynomials[简单模拟--多项式相加]
    A1046 Shortest Distance [简单模拟--卡算法复杂度]
    1009 说反话
    usb之配置描述符
  • 原文地址:https://www.cnblogs.com/hunterCecil/p/5690374.html
Copyright © 2011-2022 走看看