I am trying to dig deeper into JavaScript OOP practices. In general I get the idea, but some questions remain, especially regarding object instantiation and adding of methods.
When creating a constructor function, I have used these two versions in the past:
function MyConstructor(someArg) {
this.arg = someArg;
}
var MyConstructor = function(someArg) {
this.arg = someArg;
}
Both can be initialized in the same way, but are they identical? I am asking because in one of them, the object’s name is the function’s name, in the other one the actual object is created in an anonymous function.
When it comes to adding methods to the object, I encountered several variations which is really confusing to me because I don’t really understand if it’s just a different syntax or if they work differently.
This one adds a function to the prototype of MyConstructor
, which means all instances will have access to it, also objects extending MyConstructor
because it’s in the prototype chain.
MyConstructor.prototype.showArg = function() {
console.log(this.arg);
}
Sometimes I also see things like this:
MyConstructor.prototype = {
showArgument:function() {
console.log(this.arg);
},
};
Is this the same as in the first example (MyConstructor.prototype.showArg = function()…
)?
Then I've also encountered a syntax like this, which doesn’t work for me – is it because showArg
is added only to one specific instance, but not to the prototype?
MyConstructor.showArg = function() {
console.log(this.arg);
}
Also, there also seems to be a jQuery way of doing this:
$.extend(MyConstructor.prototype, {
showArgument:function() {
console.log(this.arg);
},
});
This is probably the same as the first two example because it adds properties to the prototype, it it?