So I can reuse code in more than one place on a web page, I am converting it to Object Oriented Javascript. The original code looks like this:
foo = 42;
function bar(a,b) {
foo = a * foo + b;
}
...
bar(1,1)
I think I want it to look like this:
function Example() {
this.foo = 42;
this.bar = function() {
this.foo = a * this.foo + b;
}
}
var one = new Example();
var two = new Example();
...
one.bar(1,1);
two.bar(2,3);
However, I'm not sure I'm using 'this' correctly inside the nested function. I've noticed that a few of the functions I'm going to convert are event handlers that already refer to 'this' in their body. How do I distinguish the 'this' already in the event handler from the 'this' I want to use to access my local variables?
Create a local var in the Example class/function and then you can reference the appropriate this object.
function Example() {
var self = this;
this.foo = 42;
this.bar = function() {
self.foo = a * self.foo + b;
}
}
Related
I can do something like this:
var foo = ...// some function assignment
var fooString = foo.toString()
...
// add some alert to foo
...
var fooWithAlert = new Function(forStringWithAlert)
Is there a way to mutate first foo instead of creating new function?
I need it to monkey patch some dependency without recreating whole hierarchy of objects.
I need to patch a constructor function in a library, just add an alert on every call. But without juggling with prototypes
No, you can't modify the function foo refers to. You can only make foo refer to a new function that does what you want. One way to do that is to use your toString approach, but it's best to avoid that if at all possible, because the function you get as a result will not be the same as the original; the scope it has access to will be different.
Usually, you do want a proxy/wrapper, e.g.:
// The original foo
var foo = function(arg) {
return "original foo says '" + arg + "'";
};
console.log(foo("bar"));
// Let's wrap it
(function() {
var originalFoo = foo;
foo = function() {
return originalFoo.apply(this, arguments) + " plus updated foo";
};
})();
console.log(foo("bar"));
This doesn't create a hierarchy of objects or similar, it just wraps foo.
If foo is a constructor function (let's call it Foo), you'll also want to copy Foo.prototype:
// The original Foo
var Foo = function(arg) {
this.value = "original foo";
this.arg = arg;
};
Foo.prototype.getArg = function() {
return this.arg;
};
var f1 = new Foo("bar");
console.log(f1.getArg());
// Let's wrap it
(function() {
var originalFoo = Foo;
Foo = function() {
var rv = originalFoo.apply(this, arguments);
this.arg += " (plus more from augmented foo)";
return rv;
};
Foo.prototype = originalFoo.prototype;
})();
var f2 = new Foo("bar");
console.log(f2.getArg());
And of course, if you need to wrap a function on Foo.prototype, you can do it just like foo in my first example:
// The original Foo
var Foo = function(arg) {
this.value = "original foo";
this.arg = arg;
};
Foo.prototype.getArg = function() {
return this.arg;
};
var f = new Foo("bar");
console.log(f.getArg());
// Let's wrap its getArg
(function() {
var originalGetArg = Foo.prototype.getArg;
Foo.prototype.getArg = function() {
return originalGetArg.apply(this, arguments) + " updated";
};
})();
console.log(f.getArg());
Note how it doesn't matter that we wrapped the prototype function after creating the f object.
I am confused about using apply or call method correctly.
I know that apply is passing an array to the function and call is passing strings to a function.
For example the code below, what does "this"really have to do with the code? if it has nothing to do with this code, then can anyone give me an example when "this" is implementing appropriately?
function myFunction(a, b) {
return a * b;
}
myArray = [10,2];
myFunction.apply(this, myArray);
It's the context for the function. If you have this.something inside the function, it will access that particular property from that context object.
function foo(bar) {
this.bar = bar;
}
foo.apply(this, ['Hello']); //calling foo using window as context (this = window in global context in browser)
console.log(this.bar); //as you can see window.bar is the same as this.bar
console.log(window.bar);
var ctx = {}; //create a new context
foo.apply(ctx, ['Good night']);
console.log(ctx.bar); //ctx now has bar property that is injected from foo function
Open up your dev console to see result.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
this is the scope of the Apply/Call function. An example is:
function test() {
alert(this.a);
}
(function () {
this.a = "test";
test();//test
var self = this;
(function () {
this.a = "Foo";
test();//Foo
test.apply(self, []);//test
}());
}());
The first argument will be the this in your function.
ie:
var p = {"name":"someone"};
function myFunction(a, b) {
console.log(this);
return a*b;
}
var myArray = [10,2];
myFunction.apply(p, myArray); //log output shows {"name":"someone"}
I always have difficulty grasping new concepts without seeing a real, basic, working example of what I am reading about. While I like the other explanation on stackoverflow, I'd really like to see a very basic example showing the difference between methods and functions in JavaScript that I can quickly run to learn more.
A method is just a function that is a property of an object. It's not a different type of object in javascript, but rather method is just the descriptive name given to a function that is defined as a property of an object.
var myObj = {};
myObj.go = function() {alert("hi");}
myObj.go();
In this example, go is a method on the myObj object.
When a method is called as in the above example myObj.go(), then the value of the this pointer is set to the object that was involved in the invocation of the method (in this case myObj).
Since global functions are also implicitly properties on the window object, one could say that global functions are also methods on the window object, but you do not need the window designation in order to call them.
Local functions like inner() in this function are just functions and not methods as they are not attached to a particular object:
function main() {
function inner() {
alert("hi");
}
inner();
}
This is a function and a function call:
function myFunction(){
alert("This is a function!");
}
myFunction();
This, on the other end, is a method call, because it is a member function of an object.
message.toUpperCase();
Here's the full code to create a class/methods and a call:
function Circle(x,y,r) {
this.xcoord = x;
this.ycoord = y;
this.radius = r;
}
Circle.prototype.retArea = function () {
return ( Math.PI * this.radius * this.radius );
};
var aCircle = new Circle(1,2,3);
var a = aCircle.retArea();
example:
function:
var f1 = function fBase() { ... }
function f2() { ... }
var f3 = function() { ... }
f1()
f2()
f3()
method:
var c = function oBase() {
this.method1 = function() { ... };
}
c.prototype.method2 = function() { ... }
var o = new c()
o.method1()
o.method2()
method json:
var o = { method1: function() { ... } }
o.method2 = function() { ... }
o.method1()
o.method2()
A function is a type which can be used to define a piece of code that can be executed by using call ("()") operator and may return data to the caller.
e.g.
define
function sayHello(){
return "Hello";
}
use
var result = sayHello();
Now, result will contian "Hello".
A method is a function that is defined inside an object and accessible through a property. For example, slice is function defined over all string instances
e.g.
define
var obj = {
sayHello : function(){
return "Hello";
}
};
you can also define methods outside the object definition
var obj = {};
obj.sayHello = function(){
return "Hello";
};
use
var result = obj.sayHello();
We use methods in object oriented programming.
Refer:
Functions at MDN
Objects at MDN
I can't think of a way to explain what I'm after more than I've done in the title, so I'll repeat it. Is it possible for an anonymous function called from within an object to have access to that object's scope? The following code block should explain what I'm trying to do better than I can:
function myObj(testFunc) {
this.testFunc = testFunc;
this.Foo = function Foo(test) {
this.test = test;
this.saySomething = function(text) {
alert(text);
};
};
var Foo = this.Foo;
this.testFunc.apply(this);
}
var test = new myObj(function() {
var test = new Foo();
test.saySomething("Hello world");
});
When I run this, I get an error: "Foo is not defined." How do I ensure that Foo will be defined when I call the anonymous function? Here's a jsFiddle for further experimentation.
Edit: I am aware of the fact that adding the line var Foo = this.Foo; to the anonymous function I pass in to my instance of myObj will make this work. However, I'd like to avoid having to expose the variable inside the anonymous function--do I have any other options?.
Should be this.Foo:
var test = new myObj(function() {
var test = new this.Foo();
test.saySomething("Hello world");
});
http://jsfiddle.net/grzUd/5/
Or alternatively using with:
var test = new myObj(function() {
with (this) {
var test = new Foo();
test.saySomething("Hello world");
}
});
http://jsfiddle.net/grzUd/6/
Change var test = new Foo(); to var test = new this.Foo();.
Edit: Or you could pass it as a parameter.
function myObj(testFunc) {
this.testFunc = testFunc;
var Foo = function (test) {
this.test = test;
this.saySomething = function(text) {
alert(text);
};
};
this.testFunc(Foo);
}
var test = new myObj(function(Foo) {
var test = new Foo();
test.saySomething("Hello world");
});
You seem to be confused about the difference between identifier resolution on the scope chain and property resolution.
Foo is a property of an instance of myObj (i.e. it's an object property). Calling new Foo will resolve Foo as a variable on the scope chain, which isn't the right place to look for it. That's why Petah's answer tries to use with, to put the object properties of the this object on the scope chain.
What is the difference between declaring a variable with this or var ?
var foo = 'bar'
or
this.foo = 'bar'
When do you use this and when var?
edit: is there a simple question i can ask my self when deciding if i want to use var or this
If it is global code (the code is not part of any function), then you are creating a property on the global object with the two snippets, since this in global code points to the global object.
The difference in this case is that when the var statement is used, that property cannot be deleted, for example:
var foo = 'bar';
delete foo; // false
typeof foo; // "string"
this.bar = 'baz';
delete bar; // true
typeof bar; "undefined"
(Note: The above snippet will behave differently in the Firebug console, since it runs code with eval, and the code executed in the Eval Code execution context permits the deletion of identifiers created with var, try it here)
If the code is part of a function you should know that the this keyword has nothing to do with the function scope, is a reserved word that is set implicitly, depending how a function is called, for example:
1 - When a function is called as a method (the function is invoked as member of an object):
obj.method(); // 'this' inside method will refer to obj
2 - A normal function call:
myFunction(); // 'this' inside the function will refer to the Global object
// or
(function () {})();
3 - When the new operator is used:
var obj = new Constructor(); // 'this' will refer to a newly created object.
And you can even set the this value explicitly, using the call and apply methods, for example:
function test () {
alert(this);
}
test.call("hello!"); //alerts hello!
You should know also that JavaScript has function scope only, and variables declared with the var statement will be reachable only within the same function or any inner functions defined below.
Edit: Looking the code you posted to the #David's answer, let me comment:
var test1 = 'test'; // two globals, with the difference I talk
this.test2 = 'test'; // about in the beginning of this answer
//...
function test4(){
var test5 = 'test in function with var'; // <-- test5 is locally scoped!!!
this.test6 = 'test in function with this'; // global property, see below
}
test4(); // <--- test4 will be called with `this` pointing to the global object
// see #2 above, a call to an identifier that is not an property of an
// object causes it
alert(typeof test5); // "undefined" since it's a local variable of `test4`
alert(test6); // "test in function with this"
You can't access the test5 variable outside the function because is locally scoped, and it exists only withing the scope of that function.
Edit: In response to your comment
For declaring variables I encourage you to always use var, it's what is made for.
The concept of the this value, will get useful when you start working with constructor functions, objects and methods.
If you use var, the variable is scoped to the current function.
If you use this, then you are assigning a value to a property on whatever this is (which is either the object the method is being called on or (if the new keyword has been used) the object being created.
You use var when you want to define a simple local variable as you would in a typical function:-
function doAdd(a, b)
{
var c = a + b;
return c;
}
var result = doAdd(a, b);
alert(result);
However this has special meaning when call is used on a function.
function doAdd(a, b)
{
this.c = a + b;
}
var o = new Object();
doAdd.call(o, a, b);
alert(o.c);
You note the first parameter when using call on doAdd is the object created before. Inside that execution of doAdd this will refer to that object. Hence it creates a c property on the object.
Typically though a function is assigned to a property of an object like this:-
function doAdd(a, b)
{
this.c = a + b;
}
var o = new Object();
o.doAdd = doAdd;
Now the function can be execute using the . notation:-
o.doAdd(a, b);
alert(o.c);
Effectively o.doAdd(a, b) is o.doAdd.call(o, a, b)
var foo = 'bar'
This will scope the foo variable to the function wrapping it, or the global scope.
this.foo = 'bar'
This will scope the foo variable to the this object, it exactly like doing this:
window.foo = 'bar';
or
someObj.foo = 'bar';
The second part of your question seems to be what is the this object, and that is something that is determined by what context the function is running in. You can change what this is by using the apply method that all functions have. You can also make the default of the this variable an object other than the global object, by:
someObj.foo = function(){
// 'this' is 'someObj'
};
or
function someObj(x){
this.x=x;
}
someObj.prototype.getX = function(){
return this.x;
}
var myX = (new someObj(1)).getX(); // myX == 1
In a constructor, you can use var to simulate private members and this to simulate public members:
function Obj() {
this.pub = 'public';
var priv = 'private';
}
var o = new Obj();
o.pub; // 'public'
o.priv; // error
Example for this and var explained below:
function Car() {
this.speed = 0;
var speedUp = function() {
var speed = 10; // default
this.speed = this.speed + speed; // see how this and var are used
};
speedUp();
}
var foo = 'bar'; // 'var can be only used inside a function
and
this.foo = 'bar' // 'this' can be used globally inside an object