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";}
};
}开发者_JS百科;
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
var A = function () {
this.workingTest = function () {return "OK";};
};
The problem is that your original A
function was creating and returning a direct instance of Object
instead of using the instance of A
that was created by the new
operator and bound to this
.
To understand this, try running
var B = function () { return { x: 42 }; }
var C = function () { this.x = 42; }
var b = new B;
var c = new C;
alert("b.constructor === B : " + (b.constructor === B)); // false
alert("b.constructor === Object : " + (b.constructor === Object)); // true
alert("c.constructor === C : " + (c.constructor === C)); // true
So because B
returns a new object, the value it returns is no longer an instanceof B
and does not use B
's prototype.
Because A
returns a separate object, a
is not an instance of the A
class; rather, it's an ordinary object which happens to be returned by the A
function.
It is not connected to A
or its prototype
at all.
Instead, you need to assign workingTest
to this
inside the constructor and not return anything at all:
var A = function () {
this.workingTest = function () { return "OK"; };
};
Because you extend A
's prototype while the new A()
returns an "anonymous" object.
In a modern browser, you can keep your interesting prototyping approach with:
var A = {
workingTest: function () {return "OK";}
};
A.notWorkingTest = function () {return "Yes it does";};
var a = Object.create (A);
a.workingTest(); // "OK"
a.notWorkingTest(); // "Yes it does"
a.extending = function () {return "extended";};
var b = Object.create(a);
b.workingTest(); // "OK"
b.extending(); // "extended"
This works according to the ES5 spec.
You defined A
as a function that returns an object literal. Using the new
keyword when calling a function implies that it is a special type of function, namely a constructor. Constructors in JavaScript must be written in a specific way, setting properties using the this
keyword.
var A = function () {
this.workingTest = function () {return "OK";};
};
精彩评论