Override this.method = function() inside of a var x = function() - javascript

I have a Javascript Object:
var Dog = function() {
this.speak = function() {
return 'woof'
}
this.trick = function() {
return 'sitting'
}
}
I want to make a new object, Cat, that is based on Dog but has a different speak method:
var Cat = ???
...
this.speak = function() {
return 'meow'
}
...
So I can ultimately do this:
var tabby = new Cat();
tabby.speak() //returns 'meow'
tabby.trick() //returns 'sitting'
I have little experience with 'object-oriented Javascript' and can't seem to find an example online that reflects what I want to do, nor do I know what keywords to search for.
I thought it would be something similar to how I override functions in Backbone, but this seems different:
var Cat = Dog.extend({
//the speak function below would override the one that returns 'woof'
speak: function() {
return 'meow'
}
});
Any help is appreciated!
(Above is the simplified version of my ultimate goal - I want to override the render method inside of Rickshaw.Graph.Axis.X)

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 */);.

Given your current approach, you could do this:
var Dog = function() {
this.speak = function() {
return 'woof'
}
this.trick = function() {
return 'sitting'
}
}
var Cat = function() {
Dog.call(this)
this.speak = function() {
return 'meow'
}
}
Though we're not using prototypal inheritance here. We're just assigning own properties directly to the objects. This is less efficient than using shared, inherited methods. Not to mention that the Cat creates the speak method on the Dog, then overwrites it immediately.
var tabby = new Cat();
tabby.speak() //returns 'meow'
tabby.trick() //returns 'sitting'

function Dog() {}
Dog.prototype.speak = function() {
return 'woof';
};
Dog.prototype.trick = function() {
return 'sitting';
};
function Cat(){}
Cat.prototype = Object.create(Dog.prototype);
Cat.prototype.speak = function() {
return 'meow';
};
var fluffy = new Cat();
fluffy.speak(); // 'meow'
fluffy.trick(); // 'sitting'
Basically, you want to do some Googling for "prototypal inheritance".

Same concept as the other answers but here is the javascript secret inherits function slightly simplified from google closure - https://code.google.com/p/closure-library/source/browse/closure/goog/base.js#1578
var inherits = function(child, parent) {
function tmp () {};
tmp.prototype = parent.prototype;
child.superClass_ = parent.prototype;
child.prototype = new tmp;
child.prototype.constructor = child;
};
Now you can
var Dog = function() {};
Dog.prototype.speak = function(){
return 'woof';
}
Dog.prototype.trick = function(){
return 'sitting';
}
var Cat = function(){};
inherits(Cat, Dog); //weird
Cat.prototype.speak = function(){
return "meow";
};
var HouseCat = function(){};
inherits(HouseCat, Cat);
HouseCat.prototype.speak = function(){
return "purr";
};
var dog = new Dog();
var cat = new Cat();
var houseCat = new HouseCat();
console.log(dog.speak()); //woof
console.log(cat.speak()); //meow
console.log(houseCat.speak()); //purr
console.log(houseCat.trick()); //sitting
console.log(cat instanceof Dog); //true
console.log(houseCat instanceof Cat); //true
console.log(houseCat instanceof Dog); //true
console.log(dog instanceof Cat); //false
console.log(cat instanceof HouseCat); //false

Related

Interesting JavaScript inheritance pattern

I have recently watched a video where Douglas Crockford was explaining inheritance patterns of Javascript. The video itself is pretty old - it was filmed 6 years ago - but still useful. In that video he showed one inheritance pattern he kinda invented (although I am not sure who the author is). This is the code using his approach:
// imitation of new operator
function objectConstructor(obj, initializer, methods) {
// create prototype
var func, prototype = Object.create(obj && obj.prototype);
// add methods to the prototype
if(methods) Object.keys(methods).forEach(function(key) {
prototype[key] = methods[key];
});
// function that will create objects with prototype defined above
func = function() {
var that = Object.create(prototype);
if(typeof initializer === 'function') initializer.apply(that, arguments);
return that;
}
func.prototype = prototype;
prototype.constructor = func;
return func;
}
var person = objectConstructor(Object, function(name) {
this.name = name;
}, {
showName: function() {
console.log(this.name);
}
});
var employee = objectConstructor(person, function(name, profession) {
this.name = name;
this.profession = profession;
}, {
showProfession: function() {
console.log(this.profession);
}
});
var employeeInfo = employee('Mike', 'Driver');
employeeInfo.showName(); // Mike
employeeInfo.showProfession(); // Driver
Unfortanately, he didn't show the invocation. So, this part
var employeeInfo = employee('Mike', 'Driver');
employeeInfo.showName();
employeeInfo.showProfession();
is mine. It generally works, but it turns out that I repeat this.name = name; for both "classes" - person and employee. I played around but I didn't manage to make it work properly without that repetition. Seems I cannot get name because such a property isn't contained in the prototypal chain for employee. I didn't succeed either in mixing in stuff like person.call(this, arguments). So, apart from whether it is cool/nice/smart/sensible etc. or not in 2017, how could I remove this.name = name; from employee and get the same result? Or everything is ok and this approach doesn't suppose it?
Here is your snippet with 2 small modifications so that you can do a super(name) type of call.
I've placed comments were I've made the modifications.. with prefix keith:
// imitation of new operator
function objectConstructor(obj, initializer, methods) {
// create prototype
var func, prototype = Object.create(obj && obj.prototype);
// add methods to the prototype
if(methods) Object.keys(methods).forEach(function(key) {
prototype[key] = methods[key];
});
// function that will create objects with prototype defined above
func = function() {
var that = Object.create(prototype);
if(typeof initializer === 'function') initializer.apply(that, arguments);
return that;
}
func.prototype = prototype;
//keith: store the initialization in constructor,
//keith: as func is already creating the object..
prototype.constructor = initializer;
return func;
}
var person = objectConstructor(Object, function(name) {
this.name = name;
}, {
showName: function() {
console.log(this.name);
}
});
var employee = objectConstructor(person, function(name, profession) {
//keith: call our super person(name)
person.prototype.constructor.call(this, name);
this.profession = profession;
}, {
showProfession: function() {
console.log(this.profession);
}
});
var employeeInfo = employee('Mike', 'Driver');
employeeInfo.showName(); // Mike
employeeInfo.showProfession(); // Driver
Since the func constructor completely disregards this, passing any context to it via call or apply will not work. Creating a way to copy over the super class' properties after creating an object is one of the ways you could accomplish your task.
// imitation of new operator
function objectConstructor(obj, initializer, methods) {
// create prototype
var func, prototype = Object.create(obj && obj.prototype);
// add methods to the prototype
if(methods) Object.keys(methods).forEach(function(key) {
prototype[key] = methods[key];
});
// function that will create objects with prototype defined above
func = function() {
var that = Object.create(prototype);
if(typeof initializer === 'function') initializer.apply(that, arguments);
return that;
}
func.prototype = prototype;
prototype.constructor = func;
return func;
}
function copyProperties(source, target) {
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
}
var person = objectConstructor(Object, function(name) {
this.name = name;
}, {
showName: function() {
console.log(this.name);
}
});
var employee = objectConstructor(person, function(name, profession) {
copyProperties(person.apply(null, arguments), this);
this.profession = profession;
}, {
showProfession: function() {
console.log(this.profession);
}
});
var employeeInfo = employee('Mike', 'Driver');
employeeInfo.showName(); // Mike
employeeInfo.showProfession(); // Driver

JavaScript inheritance not working as I expected

What are the details why pe.getName() is working and pe.getSalary() is not?
var Employee = function(name) {
this.name = name;
}
Employee.prototype.getName = function() {
return this.name;
}
var PermanentEmployee = function(annualSalary) {
this.annualSalary = annualSalary;
}
PermanentEmployee.prototype.getSalary = function() {
return this.annualSalary;
}
var employee = new Employee("Mark");
PermanentEmployee.prototype = employee;
var pe = new PermanentEmployee(5000);
document.write(pe.getName());
document.write(pe.getSalary());
By doing this later in your code
PermanentEmployee.prototype = employee;
you might override this
PermanentEmployee.prototype.getSalary = function()
Try this instead:
function Employee(name) {
this.name = name;
}
Employee.prototype.getName = function() {
return this.name;
}
function PermanentEmployee(name, annualSalary) {
Employee.call(this, name); // calling parent's "constructor"
this.annualSalary = annualSalary;
}
PermanentEmployee.prototype = Object.create(Employee.prototype); // setting "inheritance"
PermanentEmployee.prototype.getSalary = function() {
return this.annualSalary;
}
var pe = new PermanentEmployee("Mark", 5000);
console.log(pe.getName());
console.log(pe.getSalary());
This is actually the expected behavior. If you want to understand why, here we go...
Consider the following schema, available in the excellent book Exploring ES6 by Dr. Axel Rauschmayer.
Before to go on, here is an important rule: in JavaScript, when you create an instance of a "class", this instance will reference the prototype property of its constructor through its dunder proto (__proto__ or [[Prototype]]).
Top left
In your example, Employee and PermanentEmployee are constructor functions. Like any function in JavaScript, they are instances of Function and they use Function.prototype.
var Employee = function(name) {
this.name = name;
}
var PermanentEmployee = function(annualSalary) {
this.annualSalary = annualSalary;
}
console.log(typeof Object.getPrototypeOf(Employee)); // ES5
console.log(typeof PermanentEmployee.__proto__); // ES6
console.log(Object.getPrototypeOf(Employee).constructor); // ES5
console.log(PermanentEmployee.__proto__.constructor); // ES6
Top right
When you write Employee.prototype.getName or PermanentEmployee.prototype.getSalary, you are actually adding new properties to the prototype property of Employee and PermanentEmployee. But Employee.prototype and PermanentEmployee.prototype are instances of Object and use Object.prototype.
var Employee = function(name) {
this.name = name;
}
Employee.prototype.getName = function() {
return this.name;
}
var PermanentEmployee = function(annualSalary) {
this.annualSalary = annualSalary;
}
PermanentEmployee.prototype.getSalary = function() {
return this.annualSalary;
}
console.log(typeof Employee.prototype);
console.log(typeof PermanentEmployee.prototype);
console.log(Employee.prototype);
console.log(PermanentEmployee.prototype);
Since PermanentEmployee.prototype is a simple object, this is not reasonable to do so: PermanentEmployee.prototype = employee.
When you do that, you override the prototype. To make a basic comparison, look at this example with an object literal:
var obj = {
foo: 'Foo'
};
obj.bar = 'Bar';
console.log(obj);
obj = 'Baz';
console.log(obj);
obj = {
foo: 'Foo',
bar: 'Bar',
baz: 'Baz'
};
console.log(obj);
You should keep this in mind when you play with prototypes...
Bottom right
In JavaScript, there are several strategies to create a "pure" object (functions and arrays are objects too...). You can:
Use an object literal: {}
Use a constructor: new Object()
Use Object.create()
In your example, you are using constructors. Therefore, your instances will use the prototype properties of your constructors, which themselves use the prototype property of Object. This is how the prototype chain works!
var Employee = function(name) {
this.name = name;
}
Employee.prototype.getName = function() {
return this.name;
}
var PermanentEmployee = function(annualSalary) {
this.annualSalary = annualSalary;
}
PermanentEmployee.prototype.getSalary = function() {
return this.annualSalary;
}
var employee = new Employee("Mark");
console.log(Object.getPrototypeOf(employee)); // ES5
console.log(employee.__proto__.constructor); // ES6
console.log(Object.getPrototypeOf(Object.getPrototypeOf(employee))); // ES5
console.log(employee.__proto__.__proto__.constructor); // ES6
But of course, if you have completely overriden your prototype somewhere, you break the prototype chain and it will not work as expected...

Static/shared property and method in JavaScript

I'm trying to have a 'class' in JS which tracks how many instances of itself have been instantiated. I am attempting to do so like this...
var myNamespace = {};
myNamespace.myClass = function () {
//fails here as .getNetInstanceNo() not recognised...
var instanceNumber = myNamespace.myClass.getNextInstanceNo();
return {
instanceNo : function() { return instanceNumber; }
}
};
myNamespace.myClass.InstanceNo = 0; //static property?
//should the class itself have this method added to it...
myNamespace.myClass.prototype.getNextInstanceNo = function () { //static method?
return myNamespace.myClass.InstanceNo++;
};
var class1 = new myNamespace.myClass();
alert('class 1 has instance of ' + class1.instanceNo() );
However this fails as the getNextInstanceNo function is not recognised. Even though I think I'm adding it through the myClass.prototype.
What am I doing wrong?
prototype is an object from which other objects inherit properties, as in when you create an instance of an object and that object doesn't have a property/method, when called, the prototype of the class in which the object belongs to is searched for that property/method, here's a simple example:
function Animal(){};
Animal.prototype.Breathe = true;
var kitty= new Animal();
kitty.Breathe; // true (the prototype of kitty breathes)
var deadCat = new Animal();
deadCat.Breathe = false;
deadCat.Breathe; // false (the deadCat itself doesn't breath, even though the prototype does have breath
As you said yourself, you don't need to define getNextInstanceNo on prototype, since that's not how static methods are defined on JavaScript, leave it right right there on the class itself, instead you can define the instanceNo method on prototype, here's how:
var myNamespace = {};
myNamespace.myClass = function () {
this.instanceNumber = myNamespace.myClass.getNextInstanceNo();
};
myNamespace.myClass.prototype.instanceNo = function () {
return this.instanceNumber;
};
myNamespace.myClass.InstanceNo = 0;
myNamespace.myClass.getNextInstanceNo = function () {
return myNamespace.myClass.InstanceNo++;
};
var class1 = new myNamespace.myClass();
alert('class 1 has instance of ' + class1.instanceNo());

Javascript prototypal inheritance and OOP

I'm creating an application that allows a user to create widgets. There are several different types of widgets, and I have defined them using protypal inheritance. i.e.
//the base widget that all widgets inherit from
var Widget = function(){}
Widget.prototype.someFunction = function(){}
//widget type A
var A = function(){}
A.prototype = new Widget();
//widget type B
var B = function(){}
B.prototype = new Widget();
I have discovered that it will be convenient to add a method on the base class that can create a new widget instance of the same type. i.e.
//the base widget
var Widget = function(){};
Widget.prototype.clone = function(){
switch(this.type){
case 'A':
return new A();
break;
case 'B':
return new B();
break;
default:
break;
}
};
Which would allow me to get a new widget of the same type using the following code:
var widgetTypeA = new A();
var cloneOfWidgetTypeA = widgetTypeA.clone();
My concern is that the base widget now has to be explicitly aware of each of the types of widgets that inherit from it. Does this violate any principles of good OOP?
Widget.prototype.clone = function() {
var constructor = window[this.type];
return new constructor();
};
Assuming that all your subclasses are declared as globals of course.
But honestly I would out those sub classes in the Widget namespace, and access them through it rather than making everything global.
Widget.A = function(){};
Widget.A.prototype = new Widget();
Widget.prototype.clone = function() {
var constructor = Widget[this.type];
return new constructor();
};
Given that your constructors are globals, you could do something like:
var global = this;
Widget.prototype.clone = function() {
if (global[this.type])
return new global[this.type]();
};
Provided each instance has a type property whose value is the name of the constructor. Or you could fix the constructor property of constructor's prototype and do:
Widget.prototype.clone = function() {
return new this.constructor();
};
function A() { };
A.prototype = new Widget();
A.prototype.constructor = A;
var a = new A();
var aa = a.clone();
However, that assumes that you don't have any parameters to pass. If you do have parameters to pass, then you likely have to know which type you are making and so can call the correct constructor anyway.
If ECMA5 is supported:
use Object.create(Object.getPrototypeOf(this));
If ECMA5 is not supported:
create an anonymous function
set the prototype of the anonymous function to the non-standard attribute this.__proto__
Example:
var Widget = function() { };
Widget.prototype.clone = function() {
/*
Non-ECMA5:
var newClone = function() {};
newClone.prototype = this.__proto__;
return new newClone();
*/
// ECMA5
return Object.create(Object.getPrototypeOf(this));
}
var A = function() { };
A.prototype = new Widget();
A.prototype.name = "I'm an A";
var B = function() { };
B.prototype = new Widget();
B.prototype.name = "I'm a B";
var x1 = new A();
var y1 = x1.clone();
console.log("y1 should be A: %s", y1.name);
var x2 = new B();
var y2 = x2.clone();
console.log("y2 should be B: %s", y2.name);
The information you need is already available in the constructor property. However, overwriting prototype will lose it as I recently explained here.
Using my own class implementation for ECMAScript version 3 or version 5, your example would look like this:
var Widget = Class.extend({
someFunction : function() {
alert('someFunction executed');
},
clone : function() {
return new this.constructor;
}
});
var A = Widget.extend();
var B = Widget.extend({
constructor : function(arg) {
Widget.call(this); // call parent constructor
this.arg = arg;
},
// override someFunction()
someFunction : function() {
alert('someFunction executed, arg is ' + this.arg)
},
// clone() needs to be overriden as well:
// Widget's clone() doesn't know how to deal with constructor arguments
clone : function() {
return new this.constructor(this.arg);
}
});
var a = new A;
var a2 = a.clone();
a2.someFunction();
var b = new B(42);
var b2 = b.clone();
b2.someFunction();

Calling method using JavaScript prototype

Is it possible to call the base method from a prototype method in JavaScript if it's been overridden?
MyClass = function(name){
this.name = name;
this.do = function() {
//do somthing
}
};
MyClass.prototype.do = function() {
if (this.name === 'something') {
//do something new
} else {
//CALL BASE METHOD
}
};
I did not understand what exactly you're trying to do, but normally implementing object-specific behaviour is done along these lines:
function MyClass(name) {
this.name = name;
}
MyClass.prototype.doStuff = function() {
// generic behaviour
}
var myObj = new MyClass('foo');
var myObjSpecial = new MyClass('bar');
myObjSpecial.doStuff = function() {
// do specialised stuff
// how to call the generic implementation:
MyClass.prototype.doStuff.call(this /*, args...*/);
}
Well one way to do it would be saving the base method and then calling it from the overriden method, like so
MyClass.prototype._do_base = MyClass.prototype.do;
MyClass.prototype.do = function(){
if (this.name === 'something'){
//do something new
}else{
return this._do_base();
}
};
I'm afraid your example does not work the way you think. This part:
this.do = function(){ /*do something*/ };
overwrites the definition of
MyClass.prototype.do = function(){ /*do something else*/ };
Since the newly created object already has a "do" property, it does not look up the prototypal chain.
The classical form of inheritance in Javascript is awkard, and hard to grasp. I would suggest using Douglas Crockfords simple inheritance pattern instead. Like this:
function my_class(name) {
return {
name: name,
do: function () { /* do something */ }
};
}
function my_child(name) {
var me = my_class(name);
var base_do = me.do;
me.do = function () {
if (this.name === 'something'){
//do something new
} else {
base_do.call(me);
}
}
return me;
}
var o = my_child("something");
o.do(); // does something new
var u = my_child("something else");
u.do(); // uses base function
In my opinion a much clearer way of handling objects, constructors and inheritance in javascript. You can read more in Crockfords Javascript: The good parts.
I know this post is from 4 years ago, but because of my C# background I was looking for a way to call the base class without having to specify the class name but rather obtain it by a property on the subclass. So my only change to Christoph's answer would be
From this:
MyClass.prototype.doStuff.call(this /*, args...*/);
To this:
this.constructor.prototype.doStuff.call(this /*, args...*/);
if you define a function like this (using OOP)
function Person(){};
Person.prototype.say = function(message){
console.log(message);
}
there is two ways to call a prototype function: 1) make an instance and call the object function:
var person = new Person();
person.say('hello!');
and the other way is... 2) is calling the function directly from the prototype:
Person.prototype.say('hello there!');
This solution uses Object.getPrototypeOf
TestA is super that has getName
TestB is a child that overrides getName but, also has
getBothNames that calls the super version of getName as well as the child version
function TestA() {
this.count = 1;
}
TestA.prototype.constructor = TestA;
TestA.prototype.getName = function ta_gn() {
this.count = 2;
return ' TestA.prototype.getName is called **';
};
function TestB() {
this.idx = 30;
this.count = 10;
}
TestB.prototype = new TestA();
TestB.prototype.constructor = TestB;
TestB.prototype.getName = function tb_gn() {
return ' TestB.prototype.getName is called ** ';
};
TestB.prototype.getBothNames = function tb_gbn() {
return Object.getPrototypeOf(TestB.prototype).getName.call(this) + this.getName() + ' this object is : ' + JSON.stringify(this);
};
var tb = new TestB();
console.log(tb.getBothNames());
function NewClass() {
var self = this;
BaseClass.call(self); // Set base class
var baseModify = self.modify; // Get base function
self.modify = function () {
// Override code here
baseModify();
};
}
An alternative :
// shape
var shape = function(type){
this.type = type;
}
shape.prototype.display = function(){
console.log(this.type);
}
// circle
var circle = new shape('circle');
// override
circle.display = function(a,b){
// call implementation of the super class
this.__proto__.display.apply(this,arguments);
}
If I understand correctly, you want Base functionality to always be performed, while a piece of it should be left to implementations.
You might get helped by the 'template method' design pattern.
Base = function() {}
Base.prototype.do = function() {
// .. prologue code
this.impldo();
// epilogue code
}
// note: no impldo implementation for Base!
derived = new Base();
derived.impldo = function() { /* do derived things here safely */ }
If you know your super class by name, you can do something like this:
function Base() {
}
Base.prototype.foo = function() {
console.log('called foo in Base');
}
function Sub() {
}
Sub.prototype = new Base();
Sub.prototype.foo = function() {
console.log('called foo in Sub');
Base.prototype.foo.call(this);
}
var base = new Base();
base.foo();
var sub = new Sub();
sub.foo();
This will print
called foo in Base
called foo in Sub
called foo in Base
as expected.
Another way with ES5 is to explicitely traverse the prototype chain using Object.getPrototypeOf(this)
const speaker = {
speak: () => console.log('the speaker has spoken')
}
const announcingSpeaker = Object.create(speaker, {
speak: {
value: function() {
console.log('Attention please!')
Object.getPrototypeOf(this).speak()
}
}
})
announcingSpeaker.speak()
No, you would need to give the do function in the constructor and the do function in the prototype different names.
In addition, if you want to override all instances and not just that one special instance, this one might help.
function MyClass() {}
MyClass.prototype.myMethod = function() {
alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
MyClass.prototype.myMethod_original.call( this );
alert( "doing override");
};
myObj = new MyClass();
myObj.myMethod();
result:
doing original
doing override
function MyClass() {}
MyClass.prototype.myMethod = function() {
alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
MyClass.prototype.myMethod_original.call( this );
alert( "doing override");
};
myObj = new MyClass();
myObj.myMethod();

Categories

Resources