I was working on a project for a while, trying to understand what I was doing When I finally got the "bug" down the fact that the code below does not work as I expected:
function alpha () {this.onion = 'onion'; Function Beta () {alert (this.onion); } Beta (); } Alpha1 = new alpha (); // Alert 'undefined' However, if I change this code:
function alpha {var self = this; This.onion = 'Onion'; Function Beta () {Alert (self.) Beta ();} Alpha 1 = New alpha (); // Warning 'Onion' This works as if I expected my After wasting a large part of life, can someone explain why this happens?
Works in this way because each function has associated its performance reference .
Although there are other ways to do so, for example:
function to use or use:
function alpha () {this.onion = 'onion'; function beta () {alert (this.onion) ;} Beta.call (this);} Var alpha1 = new alpha (); // Alert 'Onion' New ECMAScript 5th Edition Standard, Reference , Method:
presents a method of continuing the function. function alpha () {this.onion = 'onion'; var beta = function () {alar (this.onion );} .bind (this); beta ();} var alpha1 = new alpha (); // alert 'onion' Can that Beta function bind , and whether you apply it to, the is intact value . This method is not yet widely supported, currently only IE9pre3 is included in it, but you can add it to work now.
Now, I this works: this value is present on each, and the function is set to the code when the function calls Context If it is formed then this value is determined.
In your example, when you enter beta (); is not bound to any object, we can say that the context does not have base object , then, this value will refer to the global object.
Other cases occur when you are bound as a property of any such object, for example:
var obj = {foo: function () } This return === obj;}}; Obj.foo (); // true
As you can see, reference obj.bar (); In there is a base object, which is obj , and within the implemented function value will refer to it.
Note : This is an abstract concept, which is defined for language, for purposes of implementation, you can see the details in the details.
A third case where this value is set to be set, when you new operator, it will refer to a newly created object Constructor gets prototype:
function Foo () {returned; `` `` `` '`'` '`'` `` `` `` `` ` // True Foo.prototype.isprototypeOf (foo); // true
Comments
Post a Comment