Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript literal object, reference to itself

I have this example code:

var foo = {

    self: this,

    init: function(){

        self.doStuff();
    },

    doStuff: function(){
        alert('doing stuff');   
    }

}

foo.init();

Why the refence "self" doesn't work?

Thanks!

like image 938
mauriblint Avatar asked Dec 01 '11 20:12

mauriblint


People also ask

Can a JS object reference itself?

Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.

How does an object refer to itself in it's methods?

Every object can access a reference to itself with keyword this (sometimes called the this reference). When an instance method is called for a particular object, the method's body implicitly uses keyword this to refer to the object's instance variables and other methods.

Can JSON reference itself?

Unfortunately, JSON doesn't support recursion/self-referencing. This isn't JSON. Are you asking about self-references while creating an object using literal syntax? Or are you saying that you want the specified values to update automatically with changes to the referenced values?

What is an object literal in JavaScript?

The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array. Values created with anonymous functions are methods of your object. Simple values are properties.


1 Answers

Because at the time you declare the object literal this is not a reference to the object, but to whatever the calling context is.

like image 50
Mike Dinescu Avatar answered Sep 30 '22 20:09

Mike Dinescu