JavaScript object reference

I have a problem with Javascript object literals.

I would like to refer to an object as part of one of the functions:

var Obj = { name : "Johnny", dumb : function() { alert(this.name); } } 

Unfortunately, the "dumb" function is also an object. So, since dumb () does not have a 'name', it will return as undefined.

How do I get around this?

+4
source share
4 answers

dumb is an obj object method. When calling this will be set to Obj and will warn "Johnny"

Try

 var Obj = { name : "Johnny", dumb : function() { alert(this.name); } } Obj.dumb(); 
+8
source

Your code is ok. The dumb call should be:

 Obj.dumb(); // "Johnny" 

this in JavaScript is completely determined by how the function is called, not where the function is defined. If you call a function through an object property, inside the call this will refer to the object. For example, if you did this:

 var f = Obj.dumb; f(); // "undefined" 

... then you will get undefined (well, probably), because you have not set any specific value for this . In the absence of a specific value, a global object is used. ( window , in browsers.)

You can also set this using call functions or apply JavaScript functions:

 var f = Obj.dumb; f.call(Obj); // "Johnny" 

The first argument to call (and apply ) is the object to use as this . (With call any subsequent arguments are passed to the function, so f.call(Obj, 1); will be effective. In apply second argument is an array that will be used as arguments for the function, so f.apply(Obj, [1]); will be effective Obj.dumb(1); )

Additional Information:

+6
source

I think this problem is missing here. Your code is working fine.

 var Obj = { name : "Johnny", dumb : function() { alert(this.name); } } Obj.dumb(); // Alerts 'Johnny' 

This is because dumb is called on Obj , which is set to this .

EDIT: if you did the following, it would be undefined :

 var x = Obj.dumb; x(); // Alerts '' 

This is because this now window (since the function is no longer called on Obj ).

You will need .call :

 var x = Obj.dumb; x.call(Obj); // Alerts 'Johnny' 

Or .bind (ECMAScript 5, which means only modern browsers):

 var x = Obj.dumb.bind(Obj); x.call(); // Alerts 'Johnny' 
+1
source

Everything in JS is an object. this is not a "called function", it is the object on which it is called (unless you use something like apply() ).

 Obj.dumb(); 

will have this === Obj , so this.name will resolve "Johnny" .

Just make sure you call Obj.dumb() and not do something like:

 // This won't work var foo = Obj.dumb; foo(); 

... as, while foo will be the same function as dumb , the context is different (and this will be the default object: window ).

0
source

Source: https://habr.com/ru/post/1390673/


All Articles