The following code doesn’t produce a prototype like I thought it might. Can anyone see what I am doing wrong?
var A = function () {
return {
workingTest: function () {return "OK";}
};
};
A.prototype.notWorkingTest = function () {return "Not so much";};
var a = new A();
a.workingTest(); // "OK"
a.notWorkingTest(); // TypeError: "undefined_method"
Any ideas? I thought that this was the right way to extend JS classes, but I am missing something.
Change A to
The problem is that your original
Afunction was creating and returning a direct instance ofObjectinstead of using the instance ofAthat was created by thenewoperator and bound tothis.To understand this, try running
So because
Breturns a new object, the value it returns is no longer aninstanceof Band does not useB‘s prototype.