On Thu, Jul 28, 2011 at 6:04 PM, Xavier MONTILLET
<[email protected]> wrote:
> You use this whereas you didn't call the function as a constructor with the
> new operator so it bind this to the global object aka window in browsers.
Right. You usually use `this` in an object sense, where `this` refers
to the current object instance. When you use prototype and created a
fresh object with the `new` keyword. In almost all other cases you'd
use local variables.
var Person = function(){};
Person.prototype.name = "foo";
Person.prototype.sayName = function(){ alert(this.name); };
var p = new Person();
alert(p.name);
p.sayName();
The key here is that `this` refers to the object before the dot (.) or
square bracket ([]). And if you didn't use either of those, the global
object (window).*
So that's the difference between `p.sayName()` and `sayName()`, with
the first the value of `this` is `p`.
- peter
* yeah yeah, there's call/apply/bind too, let's not make it more
difficult as it already is.
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]