Preface
- I know the right code for these examples.
- What I want to know is why the following examples won’t work as expected.
Code
-
With parentheses when calling
sayItfunction.function Fruit(type){ this.type = type; this.taste = "Awful"; this.thought = sayIt(); } function sayIt(){ return this.taste+" "+ this.type; } window.onload = function (){ var lemon= new Fruit("Lemon"); alert(lemon.thought); };This will alert “undefined undefined”, why?
-
sayItfunction without parentheses.function Fruit (type){ this.type = type; this.taste = "Awful"; this.thought = sayIt; } function sayIt(){ return this.taste +" "+ this.type; } window.onload = function (){ var lemon= new Fruit("Lemon"); alert(lemon.thought); };This will literally write down the function on the alert box, why?
Thank you in advance.
Notes inline, discussion below, references and further reading at the end:
With parentheses when calling
sayItfunction.sayItfunction without parentheses.Key concepts from the above:
Functions are objects. You call a function by using a reference to it followed by
(), e.g.:means “call
fooand assign its return value tox“.You refer to the function object by just using its name, sans
(), e.g.:means “assign the function object
footox. (You could then call it:x().)Unlike some other languages, in JavaScript,
thisis defined entirely by how a function is called, not where it’s defined. When you call a function via a free variable (e.g.,foo()), you’re doing nothing to explicitly set thethisfor the function call, and sothiswill be the default value, which is the global object (windowon browsers).You can set what
thisis in two different ways:A. Put the function reference on an object property and call the function via the property’s reference to it, e.g.:
You’d then call it via the property:
Within the function call,
thiswill refer to the object from which you retrieved the property.B. Using the function object’s intrinsic
callorapplyfunctions:means “call the
sayItfunction, makingthis=lemonwithin the function call.” If you pass further arguments tocall, they’ll be passed to the function, so:means “call
sayItwiththis=lemonand pass in1,2, and3.There’s also the
applyfunction, which is just the same thing except you pass the arguments as an array rather than individually:means “call
sayItwiththis=lemonand pass in1,2, and3.I’ve blogged a bit on these subjects, FWIW:
thisMore to explore: