The Function Invocation Pattern

var o={};
o.aa = function (){
    var that = this;
    console.log(this);
    function help(){
        console.log(that);
    }
    help();
}
o.aa();
var o={};
o.aa = function (){
    var that = this;
    console.log(this);
    function help(){
        console.log(that);
    }
    help();
}
o.aa();
var o={};
o.aa = function (){
    var that = this;
    console.log(this);
    function help(){
        console.log(that);
    }
    help();
}
o.aa();
var o={};
o.aa = function (){
    var that = this;
    console.log(this);
    function help(){
        console.log(that);
    }
    help();
}
o.aa();
var o={};
o.aa = function (){
    var that = this;
    console.log(this);
    function help(){
        console.log(that);
    }
    help();
}
o.aa();
var o={};
o.aa = function (){
    var that = this;
    console.log(this);
    function help(){
        console.log(that);
    }
    help();
}
o.aa();
var o={};
o.aa = function (){
    var that = this;
    console.log(this);
    function help(){
        console.log(that);
    }
    help();
}
o.aa();
var o={};
o.aa = function (){
    var that = this;
    console.log(this);
    function help(){
        console.log(that);
    }
    help();
}
o.aa();
var o={};
o.aa = function (){
    var that = this;
    console.log(this);
    function help(){
        console.log(that);
    }
    help();
}
o.aa();
var o={};
o.aa = function (){
    var that = this;
    console.log(this);
    function help(){
        console.log(that);
    }
    help();
}
o.aa();

Run the two example respective, you will find the javascript language implement the "Function Invocation Pattern" with it's quirk.

Quote like the JavaScript the Good Part:

When a function is invoked with this pattern, this is bound to the global object. This was a mistake in the design of the language. Had the language been designed correctly, when the inner function is invoked, this would still be bound to the this variable of the outer function. A consequence of this error is that a method cannot employ an inner function to help it do its work because the inner function does not share the method's access to the object as its this is bound to the wrong value. Fortunately, there is an easy workaround. If the method defines a variable and assigns it the value of this, the inner function will have access to this through that variable. By convention, the name of that variable is that:

 

first example:

var o={};
o.aa = function (){
    console.log(this);
    function help(){
        console.log(this);
    }
    help();
}
o.aa();

 

second example:

var o={};
o.aa = function (){
var that = this;
    console.log(this);
    function help(){
        console.log(that);
    }
    help();
}
o.aa();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值