Can you explain me why does the second call of fn gives an error? The code is below.
function Test(n) {
this.test = n;
var bob = function (n) {
this.test = n;
};
this.fn = function (n) {
bob(n);
console.log(this.test);
};
}
var test = new Test(5);
test.fn(1); // returns 5
test.fn(2); // returns TypeError: 'undefined' is not a function
Here's a JSfiddle that reproduces the error http://jsfiddle.net/KjkQ2/
Your bob function is called from the global scope. Thefore, this.test is pointing at a global variable named test which is overwriting the variable you created. If you run console.log(window.test), you'll what's happening.
For your code to behave as intended, you would need one of the following
function Test(n) {
this.test = n;
// If a function needs 'this' it should be attached to 'this'
this.bob = function (n) {
this.test = n;
};
this.fn = function (n) {
// and called with this.functionName
this.bob(n);
console.log(this.test);
};
}
OR
function Test(n) {
this.test = n;
var bob = function (n) {
this.test = n;
};
this.fn = function (n) {
// Make sure you call bob with the right 'this'
bob.call(this, n);
console.log(this.test);
};
}
OR closure based objects
// Just use closures instead of relying on this
function Test(n) {
var test = n;
var bob = function (n) {
test = n;
};
this.fn = function (n) {
bob(n);
console.log(test);
};
}
When calling bob(n) within .fn, it is called within the global context (window in a browser). Now, you're setting window.test = n; which basically overwrites your function test object you created earlier.
If we you write this more explicit, it becomes more obvious:
// in the global scope, `test` gets written to the `global object`
// window.test = new Test(5);
var test = new Test(5);
test.fn(1); // returns 5
test.fn(2); // returns TypeError: 'undefined' is not a function
You can "workaround" this issue by calling bob() with an explicit context, using .call() for instance:
this.fn = function (n) {
bob.call(this,n);
console.log(this.test);
};
The root of evil here is, that the value of this is dynamically assigned during run-time. Don't get me wrong, its actually a great feature of ECMAscript - it's just the problem for you here. When you call a function, "just like that", this will always reference the global object.
You want to call bob.call(this, n), not just bob(n).
When you call bob(n), the value of this is not your object, it's window. Therefore, your test variable is replaced with 1.
In jsFiddle, the code is wrapped in a function, so window.test does not exist at first.
Related
I am trying to get private properties to work in javascript.
var obj = function() {
var a = 0;
this.run = function() {
var q = a;
a += 1;
return q;
};
};
alert(obj.run());
alert(obj.run());
I have a private variable a and a public function run, however when I call it, it throws an error saying obj.run is not a function. Does anyone know what's wrong?
Thanks
You should create instance of your obj
var o = new obj();
console.log(o.run());
console.log(o.run());
Example,
or you can use module pattern, like so
var obj = (function() {
var a = 0;
return {
run: function () {
var q = a;
a += 1;
return q;
}
};
})();
console.log(obj.run());
console.log(obj.run());
Example
the value of this is determined by how a function is called. (Context)
your obj is a function type. It has not been called, not been invoked, or no instance of it has been created yet. Thats y 'this' here refers to window object, not function obj type. Context is 'window' here
this.run = function () {
//code
}
// here the context is window, hence attaches run property to window
// object making run method accessible in global scope.
When you do
obj.run()
// remember 'this' to be window , this statement will not work,
// because obj doesn't have run property.
When you create instance of obj like
var o = new obj(); // context of 'this' is set to function now
so, if you call o.run() // it will work.
this in javascript
I want to create a prototype function that has its own scope. For this, I use an anonymous function but I cannot find a way to access the members of the object.
Here is a simplified version of what I am trying to achieve:
function F() {
this.counter = 0;
}
F.prototype.increment = (function() {
var lastIncrementTime = -1;
var caller = this; // <--- it fails here because this is the Window object
return function(time) {
if (time > lastIncrementTime) {
caller.counter++;
lastIncrementTime = time;
return caller.counter;
}
return caller.counter;
}
})();
f = new F();
f.increment();
I know it fails because this does not refer to F or the f object.
Is there a way to access it?
The immediately invoked function expression (IIFE) itself only gets invoked once, all calls to increment will use the variables as they were last left and not re-var them.
Change the invocation context using call, apply or bind
F.prototype.increment = (function() {
// this === F.prototype
// ...
}).call(F.prototype);
The this in this example context will not be instance specific, but be the prototype.
It seems like you actually want to achieve something a little bit different, where you have an independent function to initialise an instance-specific property with it's own closure, when the instance is constructed. These types of actions can consume a bit of memory so don't store too much unique data.
function F() {
this.counter = 0;
this.__init_increment(); // create `this.increment`
}
F.prototype.__init_increment = function () {
var lastIncrementTime = -1;
this.increment = function (time) {
if (time > lastIncrementTime) {
this.counter++;
lastIncrementTime = time;
}
return this.counter;
};
};
var f = new F();
f.increment(0); // 1
f.increment(0); // 1
f.increment(5); // 2
In this example, this.increment is a different function for each instance, which means you have a different closure for each instance. They are generated by a function in the prototype, which sets the instance property. The generator does not have to be in the prototype, just remember about the invocation context when applying it to your instance.
Move your var caller = this inside the anonymous function, where this will have been set appropriately.
Basically I want to do this:
someFunction() // do something
someFunction.somePropertyFunction()
someFunction() // Now someFunction is modified; it should now exhibit a different behaviour
Is this possible?
EDIT:
I'm not looking for what #Kolink was suggesting. Basically I want to augment a function's functionality by calling one of it's property function.
Specifically, I need to: 1. have access to the original function inside my property function (which is entirely doable using this), and 2. bind a new function to the original function's name (which I'm not sure if it's possible).
Just to be clear, I don't have access to the internal definition of the function that I want to augment. I want to attach a function to Function.prototype (so that it will be available as a property of the function that I want to augment), and then I will call func.augmentThis(), and then func should be augmented. But I'm not sure how, hence the question :P
Easily. Here's an example:
var derp = 123;
someFunction = function() {alert(derp);};
someFunction.somePropertyFunction = function() {derp = 456;};
someFunction(); // alerts 123
someFunction.somePropertyFunction();
someFunction(); // alerts 456
Okay, that's an oversimplified example, but yeah, it's entirely possible.
If your question is whether a function attached as a property to another function has a way to access the function to which it is attached, the answer is no. After all, the same function could be attached to any number of functions of objects.
So one alternative is to explicitly refer to the "mother" function within the function that is attached to it and intended to change its behavior:
function f (n) { alert (n + f.offset); }
f.offset = 0;
f.change_offset = function (i) { f.offset = i; };
f (1); //1
f.change_offset (100);
f (1); //101
Here, f is hard-wired into the definition of change_offset. If this bothers you, or you want something slightly more general, write a little routine to set a function as a property on another function, while binding its this to the function being attached to:
function set_func_as_func_prop ( propname, func_to_set, func_to_set_on ) {
func_to_set_on[propname] = func_to_set.bind(func_to_set_on);
}
Now you can write the function more generally
function change_offset (i) {
this.offset = i;
}
and set it on f or any other function.
set_func_as_func_prop ("change_offset", change_offset, f);
set_func_as_func_prop ("change_offset", change_offset, g);
Sort of:
function someFunction() {
return realFunction.apply(this, arguments);
}
function someFunctionA(name) {
return 'Hello, ' + name + '!';
}
function someFunctionB(name) {
return 'Goodbye, ' + name + '...';
}
var realFunction = someFunctionA;
someFunction.somePropertyFunction = function () {
realFunction = someFunctionB;
};
Sure it's possible. It's not recommended, but it's possible. For example:
function a() {
alert("a");
}
function b() {
alert("b");
}
function c() {
return c.f.apply(this, arguments);
}
c.f = a;
c.toggle = function () {
c.f = c.f === a ? b : a;
};
Now let's test it:
c(); // alerts "a"
c.toggle();
c(); // alerts "b"
See the demo: http://jsfiddle.net/LwKM3/
I want to attach a function to Function.prototype. Then I need to bind a new function to the original function's name (which I'm not sure if it's possible).
That indeed is impossible, you don't know what refers to the function. And you cannot change the internal representation of a function, which is immutable.
The only thing you can do is to create a new function and return that, to let the caller of your method use it somehow - specifically assigning it to the original variable:
somefunction = somefunction.augmentSomehow();
Your method for that will look like this:
Function.prototype.augmentSomehow = function() {
var origFn = this;
return function() {
// in here, do something special
// which might include invoking origFn() in a different way
};
};
Not sure if this helps, but I would implement described problem in following way:
// defined by somebody else - unknown to developer
var someFunction = function() {
alert("this is initial behavior");
}
someFunction(); // returns "this is initial behavior"
// defines parent object on which someFunction() is called
var parentObject = this; // returns window object (as called direclty in the
// browser)
// if you are calling someFunction from some object (object.someFunction())
// it would be:
// var parentObject = object;
// augumentThis definition
someFunction.augumentThis = function() {
var newFunction = function() {
alert("this is changed behavior");
};
parentObject.someFunction.somePropertyFunction = function() {
parentObject.someFunction = newFunction;
parentObject.someFunction();
};
};
someFunction.augumentThis(); // change function behavior
someFunction(); // "this is initial behavior"
someFunction.somePropertyFunction(); // "this is changed behavior"
someFunction(); // "this is changed behavior"
I have this Javascript constructor-
function TestEngine() {
this.id='Foo';
}
TestEngine.prototype.fooBar = function() {
this.id='bar';
return true;
}
TestEngine.prototype.start = function() {
this.fooBar();
}
TestEngine.prototype.startMethod = function() {
inter = setInterval(this.start, 200);
}
var test = new TestEngine();
test.startMethod();
Gives me this error -
Uncaught TypeError: Object [object global] has no method 'fooBar'
I tried console.log and found out that when I call this.start from within setInterval, this points to the window object. Why is this so?
The this pointer can point to one of many things depending upon the context:
In constructor functions (function calls preceded by new) this points to the newly created instance of the constructor.
When a function is called as a method of an object (e.g. obj.funct()) then the this pointer inside the function points to the object.
You can explicitly set what this points to by using call, apply or bind.
If none of the above then the this pointer points to the global object by default. In browsers this is the window object.
In your case you're calling this.start inside setInterval. Now consider this dummy implementation of setInterval:
function setInterval(funct, delay) {
// native code
}
It's important to understand that start is not being called as this.start. It's being called as funct. It's like doing something like this:
var funct = this.start;
funct();
Now both these functions would normally execute the same, but there's one tiny problem - the this pointer points to the global object in the second case while it points to the current this in the first.
An important distinction to make is that we're talking about the this pointer inside start. Consider:
this.start(); // this inside start points to this
var funct = this.start;
funct(); // this inside funct (start) point to window
This is not a bug. This is the way JavaScript works. When you call a function as a method of an object (see my second point above) the this pointer inside the function points to that object.
In the second case since funct is not being called as a method of an object the fourth rule is applied by default. Hence this points to window.
You can solve this problem by binding start to the current this pointer and then passing it to setInterval as follows:
setInterval(this.start.bind(this), 200);
That's it. Hope this explanation helped you understand a little bit more about the awesomeness of JavaScript.
Here is a neat way to do OOP with javascript:
//Global Namespace:
var MyNamespace = MyNamespace || {};
//Classes:
MyNamespace.MyObject = function () {
this.PublicVar = 'public'; //Public variable
var _privatVar = 'private'; //Private variable
//Public methods:
this.PublicMethod = function () {
}
//Private methods:
function PrivateMethod() {
}
}
//USAGE EXAMPLE:
var myObj = new MyNamespace.MyObject();
myObj.PublicMethod();
This way you encapsulate your methods and variables into a namespace/class to make it much easier use and maintain.
Therefore you could write your code like this:
var MyNamespace = MyNamespace || {};
//Class: TestEngine
MyNamespace.TestEngine = function () {
this.ID = null;
var _inter = null;
//Public methods:
this.StartMethod = function (id) {
this.ID = id;
_inter = setInterval(Start, 1000);
}
//Private methods:
function Start() {
FooBar();
console.log(this.ID);
}
function FooBar() {
this.ID = 'bar';
return true;
}
}
//USAGE EXAMPLE:
var testEngine = new MyNamespace.TestEngine();
testEngine.StartMethod('Foo');
console.log(testEngine.ID);
Initially, the ID is set to 'Foo'
After 1 second the ID is set to 'bar'
Notice all variables and methods are encapsulated inside the TestEngine class.
Try this:
function TestEngine() {
this.id='Foo';
}
TestEngine.prototype.fooBar = function() {
this.id='bar';
return true;
}
TestEngine.prototype.start = function() {
this.fooBar();
}
TestEngine.prototype.startMethod = function() {
var self = this;
var inter = setInterval(function() {
self.start();
}, 200);
}
var test = new TestEngine();
test.startMethod();
setInterval calls start function with window context. It means when start gets executed, this inside start function points to window object. And window object don't have any method called fooBar & you get the error.
Anonymous function approach:
It is a good practice to pass anonymous function to setInterval and call your function from it. This will be useful if your function makes use of this.
What I did is, created a temp variable self & assigned this to it when it is pointing your TestEngine instance & calling self.start() function with it.
Now inside start function, this will be pointing to your testInstance & everything will work as expected.
Bind approach:
Bind will make your life easier & also increase readability of your code.
TestEngine.prototype.startMethod = function() {
setInterval(this.start.bind(this), 200);
}
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