I'm new to prototyping and instantiations and therefore had a question :
For example :
function Cool_Object() {
this = new Array() // Construct new array.
//This is only for the example. I know you can't do that.
}
Cool_Object.prototype.my_method = function() {
// Some method added
};
So, if you call :
var myObject = new Cool_Object();
myObject would be an array and have a method called "my_method
" (which actually calls a function).
But the default Array object would be intact.
Thanks in advance !
You've got it a bit backwards. Just use Array.prototype
as your custom object's prototype.
function Cool_Object() {
this.my_method = function () {
return 42;
}
}
Cool_Object.prototype = Array.prototype;
var foo = new Cool_Object();
foo.my_method(); // 42
foo.push(13);
foo[0]; // 13
You can get both Array.prototype
and my_method
on Cool_Object
's prototype, without modifying Array.prototype
, by introducing an intermediate type:
function Even_Cooler() {}
Even_Cooler.prototype = Array.prototype;
function Cool_Object() {}
Cool_Object.prototype = new Even_Cooler();
Cool_Object.prototype.my_method = function () {
return 42;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With