Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  26] [ 4]  / answers: 1 / hits: 19387  / 12 Years ago, tue, september 4, 2012, 12:00:00

Since when we declare a function we get its prototype's constructor property point to the function itself, is it a bad practice to overwrite function's prototype like so:



function LolCat() {
}

// at this point LolCat.prototype.constructor === LolCat

LolCat.prototype = {
hello: function () {
alert('meow!');
}
// other method declarations go here as well
};

// But now LolCat.prototype.constructor no longer points to LolCat function itself

var cat = new LolCat();

cat.hello(); // alerts 'meow!', as expected

cat instanceof LolCat // returns true, as expected


This is not how I do it, I still prefer the following approach



LolCat.prototype.hello = function () { ... }


but I often see other people doing this.



So are there any implications or drawbacks by removing the constructor reference from the prototype by overwriting the function's prototype object for the sake of convenience as in the first example?


More From » constructor

 Answers
97

I can't see anyone mentioning best practice as far as this is concerned, so I think it comes down to whether you can see the constructor property ever being useful.



One thing worth noting is that the constructor property, if you don't destroy it, will be available on the created object too. It seems to me like that could be useful:



var ClassOne = function() {alert(created one);}
var ClassTwo = function() {alert(created two);}

ClassOne.prototype.aProperty = hello world; // preserve constructor
ClassTwo.prototype = {aProperty: hello world}; // destroy constructor

var objectOne = new ClassOne(); // alerts created one
var objectTwo = new ClassTwo(); // alerts created two

objectOne.constructor(); // alerts created one again
objectTwo.constructor(); // creates and returns an empty object instance


So it seems to me that it's an architectural decision. Do you want to allow a created object to re-call its constructor after it's instantiated? If so preserve it. If not, destroy it.



Note that the constructor of objectTwo is now exactly equal to the standard Object constructor function - useless.



objectTwo.constructor === Object; // true


So calling new objectTwo.constructor() is equivalent to new Object().


[#83255] Sunday, September 2, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devinjadong

Total Points: 711
Total Questions: 117
Total Answers: 100

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
devinjadong questions
Thu, Feb 17, 22, 00:00, 2 Years ago
Wed, Dec 8, 21, 00:00, 2 Years ago
Tue, Oct 27, 20, 00:00, 4 Years ago
Fri, Oct 18, 19, 00:00, 5 Years ago
;