Reference to object properties in Javascript

If I have a code:

function RandomObjectThatIsntNamedObjectWhichIOriginallyNamedObjectOnAccident() { this.foo = 0; this.bar = function () { this.naba = function () { //How do I reference foo here? } } } 
+4
source share
5 answers

You need a self link:

 function RandomObjectThatIsntNamedObjectWhichIOriginallyNamedObjectOnAccident() { var self = this; this.foo = 0; this.bar = function () { this.naba = function () { self.foo; //foo! } } } 
+11
source
 function SomeObject() { var self = this; this.foo = 0; this.bar = function () { this.naba = function () { self.foo; } } } 
+6
source

Try to execute

 function SomeObject() { var self = this; this.foo = 0; this.bar = function () { this.naba = function () { //How do I reference foo here? self.foo } } } 
+3
source

First: do not name your function Object , it obscures the global constructor of Object .

I see no reason why you need to assign naba inside bar instance. Why are you doing it? You can assign both bar and naba function prototype:

 function MyConstructor() { this.foo = 0; } MyConstructor.prototype.bar = function () { }; MyConstructor.prototype.naba = function () { // this.foo }; 

This ultimately depends on how you call the naba function. The fact that you assign it to this suggests that you want to call it

 var obj = new MyConstructor(); obj.naba(); 

If you want to add naba only after calling bar , you can access foo through this.foo :

 MyConstructor.prototype.bar = function () { if(!this.naba) { this.naba = function() { // this.foo }; } }; var obj = new MyConstructor(); obj.bar(); obj.naba(); 

If you need the correct / best answer, you must show how you are going to use naba .

+1
source

Interestingly, you do not need to do anything special.

The this reference works:

 function SomeObject() { this.foo = 0; this.bar = function () { this.naba = function () { alert(this.foo); // this works! } } } 

Since you always assign “methods” to the same link, this will still point to it inside the bar , and then inside naba .

0
source

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


All Articles