Question

I made a object to keep my functions became singleton, using that, i made sample methods to call and communicate each other.. but i don't get any appropriate results..

any one correct me, the singleton the way i defined here...

my sample codes:

var obj = window[obj] || {}; //singleton

obj.nameIt = function(name){

    this.name = name;

    this.getName = function(){
        return this.name;
    }

}

obj.sayIt = function(name){

    this.name = name; var that = this;

    this.sayHello = function(){
        console.log("say" + this.name);
        that.getName();//how to get result from nameIt?
    }

}

var x = obj.nameIt("af");
console.log(x.getName());//says "undefined" - how to call it?

var y = obj.sayIt("xy");
console.log(y.sayHello());//says "undefined" - how to call it?

jsfiddle here

Was it helpful?

Solution

Your code does not return anything.

obj.nameIt = function(name){

    this.name = name;

    this.getName = function(){
        return this.name;
    }
    return this;
}

obj.sayIt = function(name){

    this.name = name; var that = this;

    this.sayHello = function(){
        console.log("say" + this.name);
        return that.getName();
    }
    return this;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top