var person={}; Object.defineProperty(person,'name',{ configurable:false, //不可删除 delete person.name; value:'tao', //值 writable:false, //不可编辑的 Enumberable:false,//不可for in 循环 }); 2.对象的创建方式 1.工厂模式 function createPerson(name,age){ var obj = {}; obj.name=name; obj.age=age; obj.sayName= function(){ alert(this.name); } return obj; } 2.构造函数 function Person(name,age){ this.name=name; this.age=age; this.sayName=function(){ alert(this.name); } } 问题:每个对象都会创建一个sayName 函数 过多的内存消耗 3.原型模式 function Person(){} Person.prototype.name='tao'; Person.prototype.age=20; Person.prototype.sayName=function(){alter(this.name)}; Person.prototype={ constructor:Person,//必须的 name:'xu', age:20, sayName:function(){alter(this.name)} } 原型的问题:属性会被所有对象共享,修改其中一个 会导致其他的对象的 值被改变。 4.原型模式和构造函数相结合 function Person(){ this.name='tao'; this.age=20; } Person.prototype.sayName=function(){alert(this.name+this.age)} 5.动态原型模式 function Person(){ this.name='tao'; this.age=20; if(typeof this.sayName !='function'){ Person.prototype.sayName= function(){ alert(this.name+this.age); } } } 6.稳妥构造函数 将name设为private function Person(){ var name=name; this.sayName=function(){alert(name);}; this.setName=function(nameV){name=nameV;} } |
|
来自: 昵称11935121 > 《未命名》