"this" is a global object after using call() - javascript

I have stored the names of the methods in a list.
var list = ['fn1', 'fn2', 'fn3', 'fn4'];
I select the method using some criteria dynamically. The methods are part of a larger class that are attached using 'prototype
MyObj.prototype.selectfn = function(criteria) {
var fn = list[sel];
this[fn].call(this, arg1);
}
MyObj.prototype.fn1 = function(args) { // do something }
MyObj.prototype.fn2 = function(args) { // do something}
And so on. The problem is inside the selected "fn" function, the this variable appears as a global object even though I used call() I read the mozilla docs, but I'm not able to understand why this is so, can someone help out please?
It it helps, my environment is node.js 0.10.12.
Edit : It's a little hard to provide the correct sample code because my code involves callbacks in a lot of places, but I'll try to elucidate.
Assume two files User.js and Helper.js.
User.js
var m, h;
var Helper = require('./Helper');
function init() {
// to simplify, assume the `this` here refers to `User`
h = new Helper(this);
}
function doSomething() {
// pass some criteria string
h.selectfn(criteria);
}
Helper.js
var Helper = module.exports = function(user) {
this.user = user;
}
Helper.prototype.selectfn = function(criteria) {
// based on some criteria string, choose the function name from "list" array
// here, the string "sel" holds the selected function name
var fn = list[sel];
this[fn].call(this.user, arg1);
// if I print to console, `this.user` is correct over here, but inside the function it shows as undefined
}
Helper.prototype.fn1 = function(args) {
// Here, I talk to databases, so I have callbacks. Say, on a callback, the user property is to be updated. This is why I want to use `call()` so that the `this` refers to `User` and can be updated.
// For example, if we want to update the "last-seen" date.
this.lastseen = new Date();
}
Hope the little example made it clearer.

the first parameter of call() is your function context "this"
as example:
var someObject = {
withAFunction: function(text) { alert('hello ' + text); }
};
var testFunction = function(text) {
this.withAFunction(text);
};
testFunction.call(someObject, 'world');

I tried to review your code:
var list = ['fn1', 'fn2', 'fn3', 'fn4'];
//MyObj is copy of Object?
var MyObj = Object;
//or a preudoclass:
//var MyObj = function(){};
//inside this function you use sel and arg1 that seems undefined and use like arguments criteria that seems useless
MyObj.prototype.selectfn = function(sel,arg1) {
var fn = list[sel];
this[fn].call(this, arg1); // this is MyObj istance.
MyObj.prototype.fn1 = function(args) { console.log("fn1", args);/* do something */ }
MyObj.prototype.fn2 = function(args) { console.log("fn2",args); /* do something */ }
xxx = new MyObj();
xxx.selectfn(1,"ciao");
//call xxx.fn1("ciao");
see the console for response.

Related

Override JavaScript (window) Function

I'd like to override a function which is being made by a javascript plugin. I know how to override regular window functions, but this is different. I'm not sure how to name it, but the structure of that function is like:
window.something.function
I have no idea how to override that. I have tried the following:
var originalFunction = window.something.function;
window.something.function = function(parameter) {
alert('called');
return originalFunction(parameter);
}
But it's not working.
Does someone know a solution?
Edit:
As I have been told my question is unclear, I have edited it again using the actual names of the plug-in.
The plugin is meant to be used as:
var myColor = new jscolor(target, options)
When this is being used, there is a function "inside" the object "jscolor" which is being called when setting the value of target element. I want to override that function to add an extra functionality without changing the original js file.
Code:
if (!window.jscolor) { window.jscolor = (function () {
var jsc = {
.....
jscolor : function (targetElement, options) {
....
//Function I want to change:
this.exportColor = function (flags) {
if (!(flags & jsc.leaveValue) && this.valueElement) {
var value = this.toString();
if (this.uppercase) { value = value.toUpperCase(); }
if (this.hash) { value = '#' + value; }
if (jsc.isElementType(this.valueElement, 'input')) {
this.valueElement.value = value;
} else {
this.valueElement.innerHTML = value;
}
}
}
}
};
My attempts so far:
var origJsColor = jscolor.exportColor;
jscolor.exportColor = function(flags) {
console.log('called');
return origJsColor(flags);
}
and the window attempt above.
The jscolor code you've shown creates an object with its own copy of exportColor (one is created for each object). So to replace it, you have to replace it on each instance as the instance is created.
You can do that as a one-off in much the way you showed, just working with the instance rather than the plugin function, and using Function#call to call it with the right this:
// Get the instance
var c = new jscolor(target, options)
// Update it
var origExportColor = c.exportColor;
c.exportColor = function(flags) {
console.log('called');
return origExportColor.call(c, flags); // Note the changes on this line
};
Or instead of
return origExportColor.call(c, flags);
you might use
return origExportColor.apply(c, arguments);
...if there's any chance of the function being called with anything other than exactly one argument. (arguments is a magic pseudo-array containing the arguments used to call the function.)
If you want to do that for all instance you might create, you can put a facade in front of jscolor to do that to each instance:
var realJscolor = jscolor;
jscolor = function() {
// Call the real function, passing along all the arguments we
// get automatically (`arguments` is a magic pseudo-array)
var retVal = realJscolor.apply(this, arguments);
// If it returned a non-`null` object, we want to use that instead
// of `this`; if not, we keep using `this`
if (!retVal || typeof retVal !== "object") {
retVal = this;
}
// Slip in our version of exportColor
var origExportColor = retVal.exportColor;
retVal.exportColor = function(flags) {
console.log('called');
// (Maybe use `apply` here instead)
return origExportColor.call(retVal, flags);
};
// Return the result, in case the real function overrode `this`
return retVal;
};
jscolor.prototype = realJscolor.prototype;
Then just use jscolor normally:
var c = new jscolor(target, options);
The reason for the retVal thing is that although normally a new expression's result is a refernece to the new object created by new, a constructor function can return a non-null object reference and, if it does, the new expression's result is that object reference instead. That's why we check the return value of realJscolor.
Of course, that means that all uses of jscolor on the page that use the global will now use your updated function instead. If you don't want that, just use your own name and don't override jscolor:
var myColor = function() {
var retVal = jscolor.apply(this, arguments);
// ...and so on...
return retVal;
};
myColor.prototype = jscolor.prototype;
Usage:
var c = new myColor(target, options);
Function
function a() {alert(this)} // will print `window` obejct
is defined in the window scope. That is, it is a method of the window. Your more difficult situation comes from the fact that this is different from window if you define function as a method in another object.
var a = {method: function() {alert(this)}}
you call a.method() but see that the same window again. You need to bind your function to the parent object to make it compete method.

Properly get "this" in jQuery plugin member

I have a JavaScript module that I would like to create a jQuery plugin interface to.
The module itself is like this:
var Foo = (function () {
"use strict";
var self = {};
self.add = function (selector, otherParam)
{
// Does things unto selector.
// Precisely what it does doesn't matter.
};
return self;
}());
and is used, with success, like this:
Foo.add(a);
Now, I would like to create a plugin that interfaces to this module,
so I can use it somewhat like this:
$.fn.foo = Foo;
$.fn.foo.add = function (param) {
var selector = this;
Foo.add(selector, param);
}
$(elem).foo.add(a);
The problem I'm facing is that I can't get "this" working in .add().
The best way I managed to do it was to not have Foo be self-initializing,
and use a syntax like:
$.fn.foo = Foo;
$(elem).foo().add(a);
It works, but I find it less aesthatically pleasing and less "clean".
Is there a way to do this? Am I on the wrong approach altogether?
Thankful for any input, and I apologize in advance if this has already been answered or is unfit in any other way.
I did search for answers, but I'm not well-versed in plugin authoring nor an expert on jQuery itself.
TL;DR: I have a module like Foo above, and would like to access it's members like a jQuery plugin.
Here is a simplified version of the pattern I normally use (error checking and extra features removed).
It uses a single class function and a plugin bridge extension method to allow attachment to multiple elements. Methods are called by using a string option value:
var Foo = (function () {
"use strict";
// Constructor
function Foo($element, options){
this.$element = $element;
this.options = options
this.fooVal = 0;
}
// Create method (called from bridge)
Foo.prototype.onCreate = function(){
this.fooVal = ~~this.$element.text()
};
// Add the specified val to the elements current value
Foo.prototype.add = function (val) {
this.fooVal += val;
// Update the element text with the new value
this.$element.text(this.fooVal);
};
return Foo;
})();
// Create a bridge to each element that needs a Foo
$.fn.foo = function (options, args) {
this.each(function () {
var $element = $(this);
// Try to get existing foo instance
var foo = $element.data("Foo");
// If the argument is a string, assume we call that function by name
if (typeof options == "string") {
foo[options](args);
}
else if (!foo) {
// No instance. Create a new Foo and store the instance on the element
foo = new Foo($element, options);
$element.data("Foo", foo);
// Record the connected element on the Foo instance
foo.$element = $element;
// Call the initial create method
foo.onCreate();
}
});
}
// testing
console.clear();
$('#test').foo();
$('#button2').click(function () {
$('#test').foo("add", 2);
});
$('#button10').click(function () {
$('#test').foo("add", 10);
});
For your example Foo takes the initial value from the element text and subsequent "add" calls modify that value.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/o2u7egfy/3/
Notes:
~~ is just a fast short-cut for parseInt()
You could supply an initial value via the options parameter (ignored in first example). See following:
e.g.
// Create method (called from bridge)
Foo.prototype.onCreate = function(){
this.fooVal = this.options.value || ~~this.$element.text()
// Set initial value
this.$element.text(this.fooVal);
};
and start with
$('#test').foo({value: 999});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/o2u7egfy/4/

Javascript: Calling object methods within that object

What is the best design pattern for achieving the following (which doesn't work)?
var obj = (function() {
// code defining private variables and methods
var _obj = {
property: value,
method1: function() {
// do stuff
},
method2: function() {
// use property
var prop = _obj.property; // obviously doesn't work
// call method1
obj.method1(); // "obj" not finished being defined yet!
}
};
// obviously now I could do...
var prop = _obj.property;
return _obj;
})();
// and I could now do...
obj.method1();
A variation which I think should work is
var obj = (function() {
var property = value,
method1 = function() {
// do stuff
},
method2 = function() {
// use property
var prop = property;
// call method1
method1();
},
_obj = {
property: property,
method1: method1,
method2: method2
};
return _obj;
})();
Similarly, how does it work for objects meant to be created with the new operator? Within the constructor function itself you can write this.method(). But what if you want to keep the constructor small, only defining those things which will likely be customized upon creation, and then defining the rest in the prototype? (This seems to be the common pattern.) Can the properties / methods within the prototype interact in any way?
var MyObj = function(name) {
this.name = name;
};
var obj = new MyObj('Bob');
MyObj.prototype = {
called_often: function() {
// lots more code than just the following
return document.getElementById('someID').value;
},
global_default: 'value', // can be changed, so need to pull value when run
does_stuff: function(value) {
var str = global_default + value, // can't access global_default on its own
input = MyObj.called_often(), // doesn't work; MyObj.prototype.called_often() DOES
name = this.name; // 'this' used in the prototype doesn't work
// even within a created object
return name + input + str;
}
};
I'm sure there's better ways to achieve my result whenever I run into this problem. This code isn't situation specific and just illustrates the general problem. So you won't be able to give me an alternative for those specific situations I run into. But maybe you can help my overall thinking.
Well, from your first example:
var _obj = {
property: value,
method1: function() {
// do stuff
},
method2: function() {
// use property
var prop = this.property;
// call method1
this.method1();
}
};
That's what the this value is for.
Now, what you cannot do is refer to a property of an "under construction" object from elsewhere in the object literal syntax. (It's hard to give an example because it's just not syntactically possible.) In cases where you want to do that, you do need one or more separate assignment statements.
Guess what? You are making simple stuff complex. Pointy's answer is good, but the prototype way is better for several reasons. That's why I am describing (rather, making corrections in) the last method. Check this fiddle.
var MyObj = function(name) {
this.name = name;
};
MyObj.prototype = {
called_often: function() {
// lots more code than just the following
return 'VALUE'; //document.getElementById('someID').value;
},
global_default: 'value', // can be changed, so need to pull value when run
does_stuff: function(value) {
var str = this.global_default + value, // can't access global_default on its own
input = this.called_often(), // doesn't work; MyObj.prototype.called_often() DOES
name = this.name; // 'this' used in the prototype doesn't work
// even within a created object
return name + input + str;
}
};
var obj = new MyObj('Bob');

dynamically call local function in javascript

there are plenty of similar questions out there about calling functions by name dynamically. However, I can't find a solution to my specific problem where I have local functions inside a closure without exposing the functions to the public interface of my object.
Lets see some code (this is a fictional example)...
(function(window,$) {
MyObject = (function($) {
var obj = {};
obj.publicMethod = function(number,otherarg) {
this['privateMethod'+number].apply(this,[otherarg]);
};
var privateMethod1 = function(arg) {
//do something with arg
};
var privateMethod2 = function(arg) {
//do something else with arg
};
return obj;
})($);
window.MyObject = MyObject;
})(window,jQuery);
This doesn't work because "this" is MyObject and the local functions are not exposed.
Also I'd like to be able to check if the function exists before trying to call it.
eg.
var func_name = 'privateMethod'+number;
if($.isFunction(this[func_name])) {
this[func_name].apply(this,[otherarg]);
}
I'm not really sure how to proceed, short of exposing my private functions to the public interface, it all works then.
obj.privateMethod1 = function(arg) {
//do something with arg
};
obj.privateMethod2 = function(arg) {
//do something else with arg
};
I'm running out of ideas. Your help and advise is greatly appreciated.
The private functions are local variables and not part of any object. So, the [...] notation for accessing a property is never going to work since there is no object the private functions are properties of.
Instead, you could make two objects: private and public:
var public = {},
private = {};
public.publicMethod = function(number, otherarg) {
// `.apply` with a fixed array can be replaced with `.call`
private['privateMethod' + number].call(this, otherarg);
};
private.privateMethod1 = function(arg) {
//do something with arg
};
private.privateMethod2 = function(arg) {
//do something else with arg
};
return public; // expose public, but not private
You cannot get a reference to a local variable by a string. You have to add the local objects to a namespace:
(function(window,$) {
// Use "var MyObject = " instead of "MyObject = "!! Otherwise, you're assigning
// the object to the closest parent declaration of MyVar, instead of locally!
var MyObject = (function($) {
var obj = {};
var local = {}; // <-- Local namespace
obj.publicMethod = function(number,otherarg) {
local['privateMethod'+number].call(this, otherarg);
};
var privateMethod1 = local.privateMethod1 = function(arg) {
//do something with arg
};
var privateMethod2 = local.privateMethod2 = function(arg) {
//do something else with arg
};
return obj;
})($);
window.MyObject = MyObject;
})(window,jQuery);
I'm surprised that incorrect answer is marked as accepted. Actually you CAN get a reference to a local variable by a string. Just by using eval:
(function(window,$) {
MyObject = (function($) {
var obj = {};
obj.publicMethod = function(number,otherarg) {
// Gets reference to a local variable
var method = eval('privateMethod'+number);
// Do with it whatever you want
method.apply(this,[otherarg]);
};
var privateMethod1 = function(arg) {
//do something with arg
};
var privateMethod2 = function(arg) {
//do something else with arg
};
return obj;
})($);
window.MyObject = MyObject;
})(window,jQuery);
Actually this code is very bad and in 99.9% cases you should not use eval. But you must know how it works and what you can do with it. I myself had a few very specific cases when usage of eval was necessary.
The fact that you cannot call these functions from outside of the scope within which they are defined is a fundamental part of javascript, and indeed, all programming languages.
The only way to call these functions is to make them public. A convention based approach can be applied instead however. The underscore prefix is fairly ubiquitous and generally understood to mean "not intended to be called as a public function" eg:
obj._privateMethod1 = function(arg) {
//...
};
Assuming you only have a couple of functions to call, you can create your own version of Window to use to call the functions:
var myFuncs = {
'foo': foo,
'bar': bar
};
Then in your code:
var s = 'foo';
myFuncs[s]();
Just make sure the functions are defined when you add them to the object. In a module where the functions don't exist at load time, you can add them when the module is initialized:
var myFuncs = {};
var init = function(){
myFuncs['foo'] = foo;
myFuncs['bar'] = bar;
}

Encapsulation in javascript

I need to create simple reusable javascript object publishing several methods and parameterized constructor. After reading through several "OOP in JavaScript" guides I'm sitting here with an empty head. How on the Earth can I do this?
Here my last non-working code:
SomeClass = function(id) {
this._id = id;
}
(function() {
function intFun() {
return this._id;
}
SomeClass.prototype.extFun = function() {
return incFun();
}
})();
This is my usual approach:
MyClass = function(x, y, z) {
// This is the constructor. When you use it with "new MyClass(),"
// then "this" refers to the new object being constructed. So you can
// assign member variables to it.
this.x = x;
...
};
MyClass.prototype = {
doSomething: function() {
// Here we can use the member variable that
// we created in the constructor.
return this.x;
},
somethingElse: function(a) {
}
};
var myObj = new MyClass(1,2,3);
alert(myObj.doSomething()); // this will return the object's "x" member
alert(myObj.x); // this will do the same, by accessing the member directly
Normally the "this" keyword, when used in one of the object's methods, will refer to the object itself. When you use it in the constructor, it will refer to the new object that's being created. So in the above example, both alert statements will display "1".
An exception to this rule is when you pass one of your member functions somewhere else, and then call it. For example,
myDiv.onclick = myObj.doSomething;
In this case, JavaScript ignores the fact that "doSomething" belongs to "myObj". As a result, the "this" inside doSomething will point to another object, so the method won't work as expected. To get around this, you need to specify the object to which "this" should refer. You can do so with JavaScript's "call" function:
myDiv.onclick = function() {
myObj.doSomething.call(myObj);
}
It's weird, but you'll get used to it eventually. The bottom line is that, when passing around methods, you also need to pass around the object that they should be called on.
I usually don't worry too much about hiding the internals, although I do prefix them with underscores to mark them as not intended to be used outside the "class". Normally what I will do is:
var MyClass = function() {};
MyClass.prototype = {
_someVar : null,
_otherVar : null,
initialize: function( optionHash ) {
_someVar = optionsHash["varValue"];
_otherVar = optionsHash["otherValue"];
},
method: function( arg ) {
return _someVar + arg;
},
};
And use it as so...
var myClass = new MyClass( { varValue: -1, otherValue: 10 } );
var foo = myClass.method(6);
All vars are private:
SomeClass = function (id) {
var THIS = this; // unambiguous reference
THIS._id = id;
var intFun = function () { // private
return THIS._id;
}
this.extFun = function () { // public
return intFun();
}
}
Use THIS within private methods since this won't equal what you might expect.
From http://learn.jquery.com/code-organization/concepts/#the-module-pattern:
// The module pattern
var feature = (function() {
// private variables and functions
var privateThing = "secret";
var publicThing = "not secret";
var changePrivateThing = function() {
privateThing = "super secret";
};
var sayPrivateThing = function() {
console.log( privateThing );
changePrivateThing();
};
// public API
return {
publicThing: publicThing,
sayPrivateThing: sayPrivateThing
};
})();
feature.publicThing; // "not secret"
// logs "secret" and changes the value of privateThing
feature.sayPrivateThing();
So using returning an object that aliases its "methods" could be another way to do it.
I've read from http://www.amazon.com/Programming-Oracle-Press-Poornachandra-Sarang-ebook/dp/B0079GI6CW that it is always good practice to use getters and setters rather that accessing the variable directly from outside the object, so that would eliminate the need of returning variables by reference.
BTW you could just use this.variable to reference/declare a public variable and var variable to declare a private variable.
I know this is a late answer, but I hope it helps anyone who reads it in the future.

Categories

Resources