Usually in JavaScript, we'll define methods on a prototype, instead on the instance:
function Dog() {}
Dog.prototype.speak = function () {
return 'woof';
};
Dog.prototype.trick = function () {
return 'sitting';
};
The difference between defining a method on a prototype and on the instance is that prototypes allow you to share properties between all objects that have their prototype set to the same object. This object is where you define what properties are shared, and a prototype object can also have its own prototype, creating a prototype chain.
To create a simple example, let's take a look at a simple example:
var foo = { bar: 1 };
// create a new object with its prototype set to `foo`
var baz = Object.create(foo);
console.log(foo.bar); // 1
console.log(baz.bar); // 1
// prototype properties and values are shared
foo.bar = 2;
console.log(foo.bar); // 2
console.log(baz.bar); // 2
// this is an instance property, so the property is no longer shared
baz.bar = 3;
console.log(foo.bar); // 2
console.log(baz.bar); // 3
If you have a prototypal-inheritance system in place, this is what you'd do:
function Dog() {}
Dog.prototype.speak = function () {
return 'woof';
};
Dog.prototype.trick = function () {
return 'sitting';
};
function Cat() {}
Cat.prototype = Object.create(Dog.prototype);
Cat.prototype.constructor = Cat;
Cat.prototype.speak = function () {
return 'meow';
};
Remember that if you define a property on an instance, it will override the property set on the prototype, the prototype's prototype, and so on.
If you're looking for an answer to your specific situation where you have the methods defined on an instance (and it isn't a built-in constructor -- some have special behaviour), you need to do something a bit different:
function Cat() {
Dog.call(this);
this.speak = function () {
return 'meow';
};
}
What this does is it gives the Dog
function the current object of the instance of Cat
, on which it can set properties on. This is done by setting the value of this
in Dog
to the instance of Cat
, just for that call using func.call(/* value of this */);
.