0

In this code :

function myType(string){
    this.string = string;
    this.getName = function(){
        //return this.name;
    }
}
var myVar = new myType("string");

If I use myVar.getName(), it should return myVar. I need it to create a pop-up box that changes the whole <body> of the page, so it is important for me to get this function.

How can I do so?


Edit :

What I'm trying to do is to write a custom object. This is the steps :

  1. The user creates a object with a string;
  2. I define the functions :
    (1) call() : It calls the inline pop-up box, which changes the whole body part of the page to the pop-up box; It saves the current body in this.document_content.
    (2) hide() : It change the body to this.document_content using document.body.innerHTML.
  3. The user call by using `[Variable Name].call();"
  4. The user can close the pop-up box by clicking a <a> button in it.

The problem that I found is in 2(1), which I cannot get the name of variable to put it in the code in onclick.

What can I do?

Tool Box
  • 71
  • 11
  • 3
    I don't think that's possible. – Cerbrus May 12 '14 at 13:04
  • 8
    You cannot determine, from inside the instance of the object, under which name it is referenced. keep in mind that it could be referenced under multiple names. – Dennis May 12 '14 at 13:05
  • I don't really understand what you mean...... – Tool Box May 12 '14 at 13:05
  • yes, not possible in js. – Palash May 12 '14 at 13:06
  • Could you provide the real-life example? Because here, when calling `myVar.getName()`, you already know that `myVar`'s name is `myVar`, so I can't see the purpose of such a method... – sp00m May 12 '14 at 13:06
  • Try the answer from this question: http://stackoverflow.com/a/4602165/1977007 – Jack Allen May 12 '14 at 13:07
  • "*I cannot get the name of variable to put it in the code in onclick.*" That's the wrong way to do it anyway. Do not "create" code string for onclick attributes. Instead, assign a **handler function**, which does **reference** the current instance of your popup (by closure)! – Bergi May 12 '14 at 13:15

1 Answers1

0

If you want to change your constructor you can do so -

function myType(name, string){
    this.string = string;
    this.name = name;
    this.getName = function(){
        return this.name;
    }
}
var myVar = new myType("myVar","string");

or you can create an hash:

function myType(name, string){
        this.string = string;
        this.name = name;
        this.getName = function(){
            return this.name;
        }
        var res = {}
        res[name] = this;
        return res;
    }
// Add response to an hash
var hash = {}
$.extend(hash, new myType("myVar","string"));
griffon vulture
  • 6,594
  • 6
  • 36
  • 57