0

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

7
  • You are returning nothing from obj methods Commented Sep 12, 2013 at 9:29
  • in Obj.nameIt, i am passing a name, and setting to this.name, later i calling the method.. what is wrong here? Commented Sep 12, 2013 at 9:33
  • 2
    var x = obj.nameIt("af") here x is undefined because nameIt method returns nothing. See e.g: jsfiddle.net/PKhqF If you don't want to return something, then don't use variable, get directly obj property as: obj.name Commented Sep 12, 2013 at 9:37
  • yes, understand. as like your suggestion, how can i call "getName" - method from "this.sayHello"..? Commented Sep 12, 2013 at 9:42
  • You need to add return this; to your methods. Besides, in sayHello you won't get the name defined in nameIt, because you have just overwritten it in sayIt. You probably want a name variable local to sayIt, see jsfiddle.net/szuwe/1 Commented Sep 12, 2013 at 9:43

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.