The properties and methods which are defined inside constructor function are the properties of that object. These are not shared between instances.
The simple rule is
Anything that is added on this
instance inside constructor function is private to that instance
You can use Object.is()
to compare if different instances points to the same method.
Your Code:
function Stack() {
this.stac = new Array();
this.pop = function () {
return this.stac.pop();
}
this.push = function (item) {
console.log('In push');
this.stac.push(item);
}
}
var stack = new Stack(),
stack2 = new Stack();
console.log(Object.is(stack.push, stack2.push)); // false
Recommended Way:
It is recommended to add the common shared properties and methods on prototype. These properties and methods are shared between object instances.
function Stack2() {
this.stack = new Array();
}
Stack2.prototype.pop = function () {
return this.stack.pop();
};
Stack2.prototype.push = function (item) {
console.log('In push');
this.stack.push(item);
}
var stack = new Stack2(),
stack2 = new Stack2();
console.log(Object.is(stack.push, stack2.push)); // true