Reputation: 43
I try to aggregate a Prototype object to a JavaScript normal object:
var ModuleA = function( data ) {
this.data = data;
};
ModuleA.prototype.funcA = function() {
alert( JSON.stringify( this ) );
}
var myMainObject = {
list: []
};
$.extend( myMainObj <--------- ???ect, new ModuleA( 'Haha' ) );
myMainObject.funcA();
Now the myMainObject
will have data property and funcA
function, since I merge to the myMainObject
.
When I execute myMainObject.funcA
, the this arguments actually is myMainObject
!
To my understanding, when new a Prototype object, the function will bind to the object created with the new and pass to the constructor.
But with the jQuery extend, the this arguments is not the new object, but point to the myMainObject
, which confuse me.
Is there any idea?
Upvotes: 0
Views: 229
Reputation: 1074168
When I execute myMainObject.funcA, the this arguments actually is myMainObject !!!
Right. That's how this
works in JavaScript. This expression:
myMainObject.funcA();
looks up the funcA
property on myMainObject
, getting back a function reference, and then calls that function, setting this
during the call to the object that it got the function from (myMainObject
). That's the normal way this
is assigned.
If you want this
to be something else, you can use Function#bind
to create a function with this
baked into it, or Function#call
or Function#apply
to call a function using a specific this
value, but you probably don't want to in your scenario.
More about this
(on my blog):
this
(I need to update this to talk about ES6 arrow functions)Re your comment:
My actual intention is to let ModuleA functions has its own scope without jumble up with the myMainObject attribute
Then don't jumble ModuleA
into myMainObject
. Sounds like you want composition instead:
var myMainObject = {
list: [],
moda: new ModuleA()
};
myMainObject.moda.funcA();
Upvotes: 1
Reputation: 780851
$.extend
doesn't call constructors, it just copies the data of the object. From the documentation:
Properties that are an object constructed via new MyCustomObject(args), or built-in JavaScript types such as Date or RegExp, are not re-constructed and will appear as plain Objects in the resulting object or array.
For needs that fall outside of this behavior, write a custom extend method instead, or use a library like lodash.
Upvotes: 0