| Author |
object literal + prototyping
|
Ken Ng
Greenhorn
Joined: Feb 14, 2004
Posts: 26
|
|
Look at the below javascript code, String.prototype.test = { msg : 'world', print : function() { alert(this + ' ' + this.msg); } } var h = 'hello'; h.test.print(); // output: [object Object] world How come 'this' doesn't equal 'hello'? How to make 'this' reference variable h i.e 'hello'? Any expert can help? [ October 18, 2007: Message edited by: Bear Bibeault ]
|
 |
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 56529
|
|
The function context (this) is not an attribute of the function, but rather, of how the function is invoked. This is a very important concept in OO JavaScript. The same function can be invoked with different function contexts depending upon how it is called. In your example, you are calling the function via its reference as print which is a property of the object literal that you assigned to test. Thus, that object literal, not the String instance is the function context. By the way, please be sure to use UBB code tags when posting code to the forums. Please read this for more information. [ October 18, 2007: Message edited by: Bear Bibeault ]
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
|
 |
Ken Ng
Greenhorn
Joined: Feb 14, 2004
Posts: 26
|
|
|
So is there a way to get a reference to h? Unlike in DOM, you could use parentNode to reference the immediate ancestor.
|
 |
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 56529
|
|
No, there is no coupling. If you want the function context to be the String instance you could declare the function as a property of the String (rather than a property of a property of the String as you have) and call it via that property, or you can force it by using the Function.call() method. To be honest, your example doesn't make a whole lot of sense to me as far as why you'd set something up in that manner, so I'm not sure what other recommendations to make. [ October 19, 2007: Message edited by: Bear Bibeault ]
|
 |
 |
|
|
subject: object literal + prototyping
|
|
|