比如:
function Student(name){
this.name=name;
this.getName=function(){
return this.name
}
}我想把Student类的name属性,变为一个私有属性,还用像方法二这么声明一下嘛?还是直接方法一就可以了? 哪个好些?
方法一:
function Student(name){
this.getName=function(){
return name
}
}
方法二:
function Student(name){
var name=name;
this.getName=function(){
return name
}
}
function Student(name){
this.name=name;
this.getName=function(){
return this.name
}
}我想把Student类的name属性,变为一个私有属性,还用像方法二这么声明一下嘛?还是直接方法一就可以了? 哪个好些?
方法一:
function Student(name){
this.getName=function(){
return name
}
}
方法二:
function Student(name){
var name=name;
this.getName=function(){
return name
}
}
但是和你最开始写的那个还是有很大不同的。其this.name是需要沿着作用域链找到其_proto_上的。
但是和你最开始写的那个还是有很大不同的。其this.name是需要沿着作用域链找到其_proto_上的。
1,参数转变为局部变量是不是可以提高查找速度?当然得有很多参数和局部变量时转换才有意义,我好像在哪碰到过这种说法,想不起出处。
2,还有就是代码可读性问题,方法二和方法一的确等同,但我觉得法二的可读性更高一些,name一看就是私有属性。在这里想求证下这两个问题!
这一行没有任何意义。函数的形参就是局部变量。
例如:
function MyObject() {
//函数的私有变量
var privateVariable = 10;
function privateFunction() {
return false;
}
//特权方法
this.publicMethod = function() {
privateVariable++;
return privateFunction();
};
}
静态私有变量
(function() {
//私有变量和私有函数
var privateVariable = 10;
function privateFunction() {
return false;
}
//构造函数
MyObject = function() {
};
//公有/特权方法
MyObject.prototype.publicMethod = function() {
privateVariable++;
return privateFunction();
};
})();
(function() {
var name = "";
Person = function(value) {
name = value;
};
Person.prototype.getName = function() {
return name;
};
Person.prototype.setName = function() {
name = value;
};
})();
var person = new Person("Nicholas");
alert(person.getName()); //"Nicholas"
person.setName("Greg");
alert(person.getName()); //"Greg"
var person2 = new Person("Michael");
alert(person1.getName()); //"Michael"
alert(person2.getName()); //"Michael"
模块模式
var singleton = {
name : value,
method : function() {
//这里是方法的代码
}
};
var singleton = function() {
//私有变量和私有函数
var privateVariable = 10;
function privateFunction() {
return false;
}
//特权/公有方法和属性
return {
publicProperty : true,
publicMethod : function() {
privateVariable++;
return privateFunction();
}
};
}();
function BaseComponent() {
}
function OtherComponent() {
}
var application = function() {
//私有变量和函数
var components = new Array();
//初始化
components.push(new BaseComponent());
//公有
return {
getComponentCount : function() {
return components.length;
},
registerComponentCount : function(component) {
if(typeof component == "object") {
components.push(componet);
}
}
};
}();
application.registerComponent(new OtherComponent());
alert(application.getComponentCount());
写了行参的话..预计是跟局部变量一样, 都是在一个上下文根对象上的.所以访问起来效率一样的.
this.name=name;
this.getName=function(){
return this.name
}
}两个this.name,恐怕不是同一样东西哦。