I've recently started reading up on OOP javascript and one thing that authors seem to skip over is when an object A has been declared and suddenly I see "A.prototype.constructor =A; For example,
var A = function(){}; // This is the constructor of "A" A.prototype.constructor = A; A.prototype.value = 1; A.prototype.test = function() { alert(this.value); } var a = new A(); // create an instance of A alert(a.value); // => 1
So I run the command in firebug "var A = function(){};" and then "A.Constructor" Which reveals it's a function. I understand this.
I run the code "A.prototype.constructor = A;" and I thought this changes the A constructor from Function to A.
The constructor property of A has been changed right? Instead when I run "A.constructor" it gives me function () still.
What's the point?
I also see A.constructor.prototype.constructor.prototype.. what is going on?
constructor. The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name.
Whenever we create a JavaScript function, JavaScript adds a prototype property to that function. A prototype is an object, where it can add new variables and methods to the existing object. i.e., Prototype is a base class for all the objects, and it helps us to achieve the inheritance.
Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.
Constructor. The constructor method is a special method for creating and initializing an object created with a class . There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method.
If A inherit B using A.prototype = new B();
, you need to reset the constructor property for the class A using A.prototype.constructor=A;
, otherwise instances of A would have a constructor of B.
In your case, A.prototype.constructor === A
will return true, so A.prototype.constructor = A
did nothing.
You can quickly test out that that additional assignment does absolutely nothing:
var A = function() {}; A.prototype.constructor === A; // true -- why assign then?
Resetting the constructor property only makes sense if you've assigned a new prototype object to the class, overwriting the original constructor:
var A = function() {}; A.prototype = protoObject; // some object with members that you'd like to inherit A.prototype.constructor = A; // reset constructor
In your case, the author might be blindly doing this as good practice, even in cases where it's not necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With