此方法有个缺点,就是每次建立一个新实例都会从新建立一个新方法bash
function MyObject(){
//private variables and functions var privateVariable = 10;
function privateFunction(){
return false;
}
//privileged methods
this.publicMethod = function (){
privateVariable++;
return privateFunction();
};
}
function Person(name){
this.getName = function(){
return name;
};
this.setName = function (value) {
name = value;
};
}
var person = new Person(“Nicholas”);
alert(person.getName()); //”Nicholas”
person.setName(“Greg”);
alert(person.getName()); //”Greg”
复制代码
没有var关键字,MyObject默认为全局变量。 此方法的缺点是会共用匿名函数里面的变量函数
(function(){
//private variables and functions
var privateVariable = 10;
function privateFunction(){ return false;}
//constructor
MyObject = function(){ };
//public and privileged methods 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 (value){ name = value;};
})();
var person1 = new Person(“Nicholas”);
alert(person1.getName()); //”Nicholas”
person1.setName(“Greg”);
alert(person1.getName()); //”Greg”
var person2 = new Person(“Michael”);
alert(person1.getName()); //”Michael”
alert(person2.getName()); //”Michael”
复制代码
var singleton = function(){
//private variables and functions var privateVariable = 10;
function privateFunction(){
return false;
}
//privileged/public methods and properties
return {
publicProperty: true,
publicMethod : function(){
privateVariable++;
return privateFunction();
}
};
}();复制代码