Problems with basic prototyping in Javascript - 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

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.

Is "this" necessary in javascript apart from variable definition

My question is dead simple.
I just casually discovered that once you have defined a property with this. into an object, you don't need to prepend this. anymore when you want to call them.
So this. is really meant to be used ad definition time, like var?
I found it my self shortly after, i was referencing the window object with this. since i called my object without using new, so like it was a function.
One extra question, maybe for comments. Inside the main object, if i create a new object, and use this during the object definition, this this what will be referring to?
No, unless the context of this is a global object, such as window. Take the following example:
function Foo(bar) {
this.data = bar;
console.log(this.data); // OK
console.log(data); // ReferenceError
}
In this example, you'll get a ReferenceError: data is not defined on the first console.log(data), unless, data is a global variable. To access the instance's public member, you have to use this.data.
References:
Understanding JavaScript’s this keyword
The this keyword
There are all sorts of circumstances where you MUST use this in order to reference the right data.
These two implementations do very different things:
Array.prototype.truncate(newLen) {
// sets the length property on the current Array object
this.length = newLen;
}
Array.prototype.truncate(newLen) {
// sets a global variable named length
length = newLen;
}
var arr = [1,2,3,4,5,6,7];
arr.truncate(2);
You MUST use this in order to control what happens if you want to modify the current object. Your assumption that you can leave it off and it will still modify the current object's properties is not correct. If you leave it off, you are modifying global variables, not member properties.
So this. is really meant to be used ad definition time, like var?
No, the point of this is to be the current scope of execution. You can (and will) run into weird errors if you don't use this. For example, imagine you are an object with a property val and then on the prototype of that object you have
App.obj = function(){
this.val = 'initial';
}
obj.prototype.myMethod = function(val) {
// how would you assign argument val to object val?
}
also note that your reasoning breaks down with methods.
obj.prototype.meth2 = function(){
myMethod(); // fails where this.myMethod() would work.
}
See http://jsfiddle.net/BRsqH/:
function f(){
this.public='hello!';
var hidden='TOP SECRET!';
}
var instance=new f();
alert('Public data: '+instance.public+ /* gives "hello!" */
'\nHidden data: '+instance.hidden /* gives undefined */
);
Variables created with var are hidden and cannot be viewed nor modified outside the function which created them.
But variables created with this are public, so you can access them outside the function.
I think I got it.
I defined my object as function My_Object(){...} and then called it with MyObject(). This way the My_Object was treated as a function, not an object and therefore this == window.
So in the end I was attaching properties and methods to window instead of My_Object! That's way there were available without prepending .this.
The right way to initialize My_Object as an object is to call it like this new My_Object, isn't right?

JavaScript execution context of function argument

function Apple(){
this.name="apple";
}
function Orange(){
this.name="orange";
this.apple = new Apple();
this.apple.onCalled=function(){
alert(this.name);
}
}
Orange.prototype.onCalled=function(){
this.apple.onCalled();
}
var orange = new Orange();
orange.onCalled();
Currently the code shows "apple". How can I modify the "this.apple.onCalled=function()" line so that it shows "orange"?
i.e. I want to pass a function to another object, but when that function is called, access variables of the object who passed the function, not the variables of the object who is executing the function. An obvious solution would be to use global variables (e.g. orange.name) but I'm looking for a better way because there are many objects and I don't want to global everything.
Use a closure.
function Orange(){
this.name="orange";
this.apple = new Apple();
var that = this;
this.apple.onCalled=function() {
alert(that.name);
}
}
Have a read how keyword this works in JS, it's a bit tricky but easy to grasp.
You could write:
Orange.prototype.onCalled=function(){
this.apple.onCalled.call(this);
}
It's hard to give a general answer. The thing to understand is that this is bound upon any function call. That can be explicitly controlled with the call or apply functions, or by the . operator when accessing a function as a property of an object.
The answer Kos gives about using a closure may also be relevant; it depends on the effect you want.
Orange.prototype.onCalled=function(){
this.apple.onCalled.call(this);
}
Example: http://jsfiddle.net/XrtZe/
Have a look at: Scope in JavaScript

javascript find anonymous reference

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.

Categories

Resources