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?
-
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.Dori– Dori2011年03月31日 00:33:50 +00:00Commented Mar 31, 2011 at 0:33
1 Answer 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
Nishant
56.1k13 gold badges119 silver badges132 bronze badges
Sign up to request clarification or add additional context in comments.
lang-js