An existing function and object are as follows:
var doubling=function (x) { return x*2; }; var obj={ VAL:100, }; |
When the
function calls the pattern, this is bound to the global object. This situation can also be reacted when the object's properties and methods are initialized. The OJB is now supplemented as follows:
var obj={val:100, Prop:function () { var that=this; document.write (' Name: ' +that+ '; Type: ' +typeof ' + ' <br/> '); Return doublling (That.val); }(), Get_prop:function () { var that=this; document.write (' Name: ' +that+ '; Type: ' +typeof ' + ' <br/> '); Return doublling (That.val); }, }; |
prop uses an anonymous function that is executed, expecting that the Val value of the object be the result of the doubling () operation of the function call pattern, and Get_prop for the method invocation pattern.
When the script is loaded, Obj's property prop initialized with the statement "name: [Object Window];" Type:object "output, when using Obj.get_prop (), the statement" Name: [Object Object]; Type:object "output. The former indicates that the "this" of the function body is the global variable window, which is expected to be the obj itself.
can check the return value of the property prop and Method Get_prop (), which multiplies the Window object and returns Nan, which equals 200.
the New_prop property and the New_get_prop () method are expected to be set outside of the obj literal expression, the result will be consistent with the previous text, and the method invocation pattern will get the binding of this to itself.
Detailed Source reference: Http://www.jb51.net/article/28345.htm