replace Function.prototype does not work

S

Stone Zhong

Hi there,

I am reading the book "The Concise Guide to Dojo" and I saw some code
like below on page 11:

decafbad.school.PersonClassic.prototype = {...

I personally did a test like below

==== this code does not work ===
function Person(name) {
this.name = name;
Person.prototype = {
sayHi: function() { alert('hi ' + this.name); }
};
}
var a = new Person("JavaScript");
a.sayHi(); // I got error a.sayHi is not a function

however, if I change the code to below style , it worked,
function Person(name) {
this.name = name;
Person.prototype.sayHi = function() { alert('hi ' + this.name);
}
var a = new Person("JavaScript");
a.sayHi();

My conclusion is, a function's prototype already has some hidden
properties which might be important, replace function's prototype is
not good idea, only add property to function's prototype.
 
D

David Mark

Stone said:
Hi there,

I am reading the book "The Concise Guide to Dojo" and I saw some code
like below on page 11:

Best advice is to burn it.
decafbad.school.PersonClassic.prototype = {...
LOL.


I personally did a test like below

==== this code does not work ===
function Person(name) {
this.name = name;
Person.prototype = {
sayHi: function() { alert('hi ' + this.name); }
};

Too late to do that. The die is cast at this point.
}
var a = new Person("JavaScript");
a.sayHi(); // I got error a.sayHi is not a function

however, if I change the code to below style , it worked,
function Person(name) {
this.name = name;
Person.prototype.sayHi = function() { alert('hi ' + this.name);
}

function Person(name) {
this.name = name;
}

Person.prototype.sayHi = function() { alert('hi ' + this.name);

There is no reason to set that property on each construction.
var a = new Person("JavaScript");
a.sayHi();

My conclusion is, a function's prototype already has some hidden
properties which might be important, replace function's prototype is
not good idea, only add property to function's prototype.

Your conclusion is fine, but the observations that led you to it are faulty.
 
T

Thomas 'PointedEars' Lahn

David said:
Best advice is to burn it.

No, to recycle it. Burning it increases your carbon footprint, and it has
done enough damage already :)


SCNR

PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,589
Members
45,100
Latest member
MelodeeFaj
Top