jQuery breaking "this" in constructor?
I'm working with jQuery and creating some OOP Javascript functionality. The object and its constructor has the following structure:
var zoomin = new Object();
zoomin = function() { // This is my constructor
开发者_运维百科this.someFunction();
};
zoomin.prototype = {
someFunction: function() {
// More code here
}
};
When I create an instance of zoomin (e.g. var my_zoom = new zoomin();), the call to this.someFunction() in the constructor does not work. It seems like jQuery is taking possession of "this" and this is why it is breaking.
I would really appreciate any help on how to get this to work properly.
Thanks!
Your class definition should be like this:
function zoomin() { // This is my constructor
this.someFunction();
};
For the member method definition, it should be:
zoomin.prototype.someFunction = function() {
// More code here
};
or:
$.extend(zoomin.prototype, {
someFunction : function() {
// More code here
}
});
Hope this helps. Cheers
your code is pretty messed up. you're creating a new Object, then assigning function to the same variable. so the first statement is not necessary (and not a good practice), then assigning object (with some properties) to the prototype of the zoomin object, instead of adding a property (someFunction) to it.
try to define your constructor like this:
function zoomin(){
// this is your constructor
}
zoomin.prototype.someFunction = function(){
// this is your method.
}
var zm = new zoomin();
zm.someFunction();
See the other answers as to cleaner ways to organize this. This answer just tries to address the notion of "jQuerying breaking 'this' in constructor".
A function-object (e.g. zoomin
) must be invoked with new
to act as a Constructor (constructors are just functions, there is nothing special without new
). That is, if zoomin
is used as a callback function in jQuery then this
will be a particular (but arbitrary) object which is likely not a new object instance. This could give the illusion that jQuery breaks the constructor; however, it does not, because the constructor was not invoked with new
and thus acts like a "normal function".
If using new fnObject
then this
(inside the fnOjbect function) will always be a new "fnObject" instance. There is no way for jQuery to change this, even if it tried really, really hard.
Also, the zoomin = new Object
is 100% useless because the next line just assigns a new value (the constructor function-object) to zoomin
:-)
Happy coding.
精彩评论