I thought I know JavaScript, it seems I don't.
I want to define an object like this. (Example from http://www.phpied.com/3-ways-to-define-a-javascript-class/ )
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
Well, this looks fine, let's print the info...
apple.getInfo() //returns "red macintosh apple" as expected
OK, now take the function out and run it again...
var func = apple.getInfo; func(); //returns "undefined undefined apple"
Well, that is not what I expected. Apparently, this
is interpreted as window
. Which is not what I wanted.
My question is -- what is the idiomatic, preferred way to rewrite the apple
literal, so that apple.getInfo
returns a function, that could be run separately, but still used the object properties?