开发者

How come JavaScript {this} doesn't reference the parent object?

When making objects I assumed that this would return the object's instance - instead it seems it's something else. Why is this?

var Obj = { 
    foo : 'value',
    bar : function开发者_如何学JAVA() { return this.foo; } // Error
    bar : function() { return Obj.foo; }  // Works
}

Update: I must be missing something because in some cases using this inside objects doesn't work. How come this only references the object instance sometimes?


It does. You have a syntax issue.

Use commas to delimit object members

var Obj = { 
    foo : 'value',
    bar : function() { return this.foo; },
}

within member functions this refers to a reference to the object that the function is called on.

jsFiddle Example


Within a JavaScript function this is set depending on how the function was called.

With your example Obj, assuming you correct the syntax error and use commas between properties:

var Obj = {
  foo : 'value', // needs comma, not semicolon
  bar : function() { return this.foo; }
}

If you use the "dot" syntax on Obj to call the bar function then this will be automatically set to Obj:

Obj.bar(); // this will be Obj

That's an easy way to ensure this ends up set the way you want. But if you call the function in some other way this could be set to something else:

var nonObjBar = Obj.bar; // get a reference to the function
nonObjBar(); // this will (probably) be `window`, but depends if
             // in strict mode or inside some other function, etc

var Obj2 = { foo: "other foo" };
Obj.bar.call(Obj2); // the .call() method sets this to Obj2
                    // so bar will return Obj2's foo, "other foo"

That last example uses the .call() method on Obj.bar to invoke the function in a way that allows you to set this to anything you like (strict versus non-strict mode affects the way this works for some cases).

It might seem strange if you're coming from languages like Java, but JavaScript functions don't belong to any given object. This behaviour is pretty well defined and on purpose.


After fixing the semi-colon after 'value', this seems to work:

var Obj = { 
    foo : 'value',
    bar : function() { return this.foo; } // Error
};

alert(Obj.bar());   // alerts 'value'

See working jsFiddle here: http://jsfiddle.net/jfriend00/UFPFf/.

When you call a method on an object, the javascript engine sets the this pointer to point to the object for the duration of the method call.


You shouldn't have a semicolon after foo.

Actually when you call Obj.bar you will have this referring to Obj.

See http://jsfiddle.net/AAkbR/

var Obj = { 
    foo : 'value',
    bar : function () { return this.foo; }
};

alert(Obj.bar() === Obj.foo);

Alerts true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜