This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes HTML, CSS and JavaScript and the fly likes object literal + prototyping Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Reply Bookmark "object literal + prototyping" Watch "object literal + prototyping" New topic
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
    
  14

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
    
  14

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 ]
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: object literal + prototyping
 
Similar Threads
difference between two string object
question on strings
How can I do this..?
String concatenation
Java Pass by value? But List objects change!