You can't. Actually, the variable doesn't create the object at all. The variable just contains a reference to the object, but there could be multiple such references.
Also, there should be no need for it. Within asdf
, you can use the this
keyword to refer to the instance itself, which will be the same instance as qwer
refers to.
If you need the instance inside the methods in asdf
too, you can create a variable local to the object, like so:
function asdf () {
var memyself = this; // Store reference to `this`
this.dosomething = functon () {
var a = 1;
// Use stored reference, because `this` will refer to `dosomething` here.
mymyself.dosomethingelse();
};
this.dosomethingelse = functon () {
alert('hello');
};
}
var qwer = new asdf();
Another example, let the object bind itself to an event of an element. I deliberately put the names in the HTML already, but you could even generate all the HTML from an array of names. The HTML to start with should just contain an element in or after which to add the divs for each name.
Your object could be the one responsible for the life time of the div. If you create an object with a name as a parameter, it could create a div, add the text, attach the event handler, and even remove the div. The snippet below isn't that advanced, it just finds the element and attaches one of its methods to the click event of that element.
function asdf(element) {
// If element is a string, use it as id to fetch an actual element.
// (Some error checking required in prodction code).
if (typeof element === "string") {
element = document.getElementById(element);
}
// Store references to myself and my element.
var me = this;
me.element = element; // 'this' could be used instead of 'me'.
// Declare method
this.doSomething = function() {
alert(me.element.innerText); // Here, 'me' is required.
}
// Bind method to click event. 'this' could be used instead of 'me'.
me.element.addEventListener('click', this.doSomething);
}
// Create three object for the three elements.
// You may store the object in a variable
a = new asdf('john');
// But you don't even need to. The object can just exist without external
// reference (well, apart from the element which still uses its event handler).
new asdf('jane');
new asdf('nick');
Click a name to alert it.
<div class="button" id="john">John Doe</div>
<div class="button" id="jane">Jane Da</div>
<div class="button" id="nick">Nick Name</div>
I hope this is the problem that you are trying to solve and that this solves it. If you still need to get to quer
, you're probably implementing a bad design. If you specify more details, I (or someone else) might find a better solution for you.