0

If I write two constructors like these below:

Person(name, age) { 
 this.name = name; 
 this.age = age; 
 sayName = function() { 
 alert("hello"); 
 };
}

and

Person(name, age) { 
 this.name = name; 
 this.age = age; 
 this.sayName = function() { 
 alert("hello"); 
 };
}

What is the difference? Does

sayName

really mean something in the first code? Is it useful?

david
18.3k4 gold badges45 silver badges60 bronze badges
asked Mar 24, 2011 at 3:21
1
  • When you're asking questions about books, please include information about the work. It helps people help you, as well as correctly attributing the code. In this case, the example is from Professional JavaScript for Web Developers, Second Edition by Nicholas C. Zakas (Wrox, 2009), page 152. Commented Mar 31, 2011 at 0:33

1 Answer 1

-1

sayName in the first code is a (削除) private (削除ここまで) global function, while in second it's a privileged public function.


Update#1:

The following code pretty much summarizes what they mean

function Person(name, age) { 
 this.name = name; 
 this.age = age; 
 sayName = function() { //define in global name-space
 alert("hello"); 
 } 
 var sayNamePvt = function() { //private function
 alert("hello pvt"); 
 } 
 this.callPvt = function(){ //shows how privilege function can access private vars and functions
 sayNamePvt();
 }
}
function Person1(name, age) { 
 this.name = name; 
 this.age = age; 
 this.sayName = function() { //privilege public function 
 alert("hello1"); 
 } 
}
var one = new Person('abc', 12);
var two = new Person1('abcd', 11);
two.sayName();//privileged public access
sayName(); //global access
//one.sayName(); //ERROR: one.sayName is not a function
//one.sayNamePvt(); //ERROR: one.sayNamePvt is not a function
one.callPvt(); //privileged method can call private functions
answered Mar 24, 2011 at 3:24
Sign up to request clarification or add additional context in comments.

3 Comments

actually since there's no var keyword it's a global function
@qwertymk woops. missed the fine-line.
@jsnewman updated answer, apology for the messed up answer earlier.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.