javascript find anonymous reference - javascript

I have this inside the HTML that is creating an object in JavaScript
var myObject = new MyClass();
I know that after this I can refer to myObject and use it.
The problem is that I have the instantiation done in an anonymous way e.g.
new MyClass()
Is there a way to find then the instance so I can reuse it later in the code ? Any idea appreciated.

for example
lastOfMe = null
function myClass() {
lastOfMe = this;
this.x = 123;
}
new myClass();
alert(lastOfMe.x)
this is totally ugly though

It depends of how MyClass works...
It could have saved all the instances in a class property, but in most cases, you must assign the result of the instantiation to a variable...

Anonymous objects are just that. If you want to use your object again, why create it anonymously?
If you really must do this, then just ensure that your object will register itself somewhere, like as a property of a global or similar, so you can grab it later.

Related

The keyword this is not giving me the current object, only its parent. How do I get at the current object?

I am trying to create a variable that refers to the current object/function.
I mistakenly thought this would do it:
var fn1=function(){
var _this=this;
_this.prop='hey!';
console.log(_this);
};
The console log output the browser window object, which I found confusing until I read this:
this keyword Function context
Can anyone explain to me why, in javascript, this refers to the parent?
As a result of all of this Ive been thinking about using something like this:
var fn2=function(){
var _this=(function(){
return this;
})();
_this.prop='hey!';
console.log(_this);
};
But is there a better way or simply a correct way I am missing, to get at the current object from inside itself?
Can anyone explain to me why, in javascript, this refers to the parent?
The value of this depends on how you call the function.
If you call the function in the context of an object (foo.method()) then this is foo because it is useful to have access to the object to which the method belongs when performing OOP.
But is there a better way or simply a correct way I am missing, to get at the current object from inside itself?
What current object?
If you want to use a constructor function, then use the new keyword.
function Dog(name, breed) {
this._name = name;
this._breed = breed;
}
var myDog = new Dog("Fifi", "Poodle");
alert(myDog._name);

Private instance variable in a modular pattern

var foo = (function(){
var _blah;
function doStuff(){
//how to make _blah instance specific
//and access it here?
}
function bar(blah){
_blah = blah;
doStuff();
//this.blah = blah?
}
bar.prototype.getBlah = function(){ return _blah; };
return bar;
})();
var foos = [];
$.each([1,2,3], function(i, v){
var f = new foo(v);
foos.push(f);
});
//all instances of foo
//gets _blah set to 3
console.log(foos[1].getBlah());
I have two questions regarding the module above:
How do I set a property that is specific for each instance? Right now you can see that _blah gets overwritten, which is pretty obvious. But I need some help with the syntax. My guess is that I need to set it in the constructor like the comment. Is that the right way to do it?
How do I access the property in another method? As far as I know, this refers to window in doStuff().
http://jsfiddle.net/ncg2M/1/
How do I set a property that is specific for each instance? Right now you can see that _blah gets overwritten, which is pretty obvious. But I need some help with the syntax. My guess is that I need to set it in the constructor like the comment. Is that the right way to do it?
Yes. That's the right way to do it, using this.blah = // value, but of course this makes the variable blah accessible publicly without any restriction.
How do I access the property in another method? As far as I know, this refers to window in doStuff().
doStuff() method doesn't make a lot of sense, because when you define a function like that inside a modular, then it is usually a utility function that is used by other instance methods.

Problems with basic prototyping in Javascript

i am kinda new to javascript and i started off on something where i am stuck with some basics, the thing is i am trying to create an prototype for an object and then the references of created objects in an array and then accesing their methods but i am wrong somewhere can anyone help me with this, what i am doing is shown here :-
function Obj(n){
var name=n;
}
Obj.prototype.disp = function(){
alert(this.name);
};
var l1=new Obj("one");
var l2=new Obj("two");
var lessons=[l1,l2];
//lessons[0].disp();
//alert(lessons[0].name);
but none of these methods seem to work out.... :(
You not assigning a property of the Obj object, but just have a local variable inside the constructor. Change like this:
function Obj(n){
this.name = n;
}
Example Fiddle
Your problem is with the constructor, you are assigning the parameter to a local variable not to a field variable, change it like:
function Obj(n){
this.name=n;
}
Hope this helps
Use this:
function Obj(n){
this.name=n;
}
REASON:
Difference between var name=n; and this.name=n;
var name=n;
The variable declared with var is local to the constructor function. It will only survive beyond the constructor call if it's used in some method inside the object
this.name=n;
this is property of the object, and it will survive as long as the object does, irrespective of whether it's used or not.
Example:this in javascript

how to get instance name using jquery

in my.js
$(document).ready(function(){
a = new person();
b = new person();
...
})
person.prototype.init = function(){..}
function person(){
var someVariable;
function doSomeThing(){
...
// I need my instance name
...
}
return {doSomeThing:doSomeThing}
}
how can I get my instance name?
There's no general solution.
Objects have no intrinsic knowledge of the out-of-scope variable names to which they've been assigned.
If your variables are in global scope (which they shouldn't be) it's do-able, but only by iterating over the keys in window and finding any whose value matches this.
FWIW (unless you're writing a JS debugger) if you think you need to know this you're probably doing it wrong. JS minifiers for example often change variable names, so you shouldn't rely on them.

How to retrieve the constructor's name in JavaScript?

Assume the following program:
var SomeConstructor = function() { };
var instance = = new SomeConstructor ();
The expression instance instanceof SomeConstructor yields True, so instance has to know somehow that it was constructed by the function SomeConstructor. Is there way to retrieve the name SomeConstructor directly from instance?
(In my problem at hand, I have a hierarchy of prototypes implementing possible signals in my application. I have to access the type of a signal which shall be equivalent to the constructor used to create that signal.)
On Chrome (7.0.544.0 dev), if I do:
function SomeConstructor() { }
var instance = new SomeConstructor();
console.log(instance.constructor.name);
it prints 'SomeConstructor'...but if SomeConstructor is defined as an unnamed function as you have it, it will print an empty string instead.
If I print instance.constructor it prints the same thing as it does if I print SomeConstructor in the code you have. The instanceof operator need only compare these two values to see that they are equal to be able to return true.
This code will get the name of the constructor, as long as it is not an anonymous function:
obj.constructor.toString().match(/function (\w*)/)[1];
Why would you need the class name? Let's say you want to save and restore class instances via JSON. You could store the class name in a "type" property, and then use a resolver function in JSON.parse to restore the objects. (See the sample code on this page).
So, in theory you could use the code above to make a generalized serializer that could handle any class instance, but parsing function strings is very inefficient. This overhead can be avoided by requiring all the classes you are going to store to provide the type explicitly:
function Foo() {}
Foo.prototype.type = 'Foo';
This seems silly and redundant, which is why I started on the quest to obtain the class name implicitly. But in the end I have to give in: there is no acceptable solution in JS :-(
No. You can use x.constructor to get a direct reference to C, but it's an anonymous function so there's no way of getting its name.
If it were defined like so:
function C() { };
x = new C();
Then it would be possible to use x.constructor.toString() and parse out the name of the function from the returned string. Some browsers would also support x.constructor.name[1].
[1] https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/name
You can also declare your class this:
var C = function C() { };
Now your C class constructor is a named function (no longer an anonymous function) meaning you can do:
x = new C();
console.log(x.constructor.name); // output: C
This code of yours that needs to know the constructor, can it access the constructor function itself? If so, you can just do that instanceof thing.
It seems that you need to know it by name. This sounds dangerous. Someone can create another constructor that happen to have the same name and it will pass (unless that's what you want, of course).
At least in React it might be
this.default.name

Categories

Resources