欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript OOP 代码实例分析

程序员文章站 2022-04-28 21:33:09
javascript oop 代码实例分析 function print(str) { document.write("

javascript oop 代码实例分析

function print(str) {    
   document.write("<strong style='color:green;'>"+str+"</strong>");    
}    
function println(str){    
    if(str){    
        document.write("<strong style='color:green;'>"+str+"</strong><br/>");    
    }    
    else{    
        document.write("<br/>");    
    }    
}    
var obj = {};  
object.defineproperty(obj,"name",{configurable:false,//readonly  
                    value:"xiuye",  
                    enumerable:false,//not for in  
                    writable:false  
      
});  
  
println(obj.name);  
obj.name="javascript";  
println(obj.name);  
println("output property start:");  
for(property in obj){  
    println(property);  
}  
println("end");  
  
object.defineproperty(obj,"age",{  
   get:function(){  
       return 18;  
   } ,  
   set:function(value){  
       this._age=value;//不能设置为age否则stack error  
   }  
});  
  
println(obj.age);  
obj.age=99;  
println(obj.age);  
println(obj._age);  
  
obj.__definegetter__("year",function(){  
   return 2018;   
});  
obj.__definesetter__("year",function(value){  
    this._year = value;  // maximum call stack size exceeded  
});  
println(obj.year);  
obj.year=2230;  
println(obj.year);  
println(obj._year);  
  
object.defineproperties(obj,{  
   hobby:{  
       value:"美食",  
       configurable:false,  
       enumerable:false,  
       writable:false  
   },  
   level:{  
       value:100,  
       configurable:false,  
       enumerable:false,  
       writable:false  
   }  
     
});  
  
println(obj.hobby);  
println(obj.level);  
  
function user(){  
      
}  
user.prototype.name="xiuye";  
  
var u1 = new user();  
println(u1.name);  
var u2 = new user();  
println(u2.name);  
  
// println(u1.prototype);//error undefined  
// println(u2.prototype);  
u1.prototype = {};  
u1.prototype.name="javascript";  
println(u1.prototype.name);  
println(u1.name);  
// println(u2.prototype.name);  
  
  
// u2.prototype.name="javascript";  
// println(u1.prototype);  
// println(u2.prototype);  
xiuye  
xiuye  
output property start:  
end  
18  
18  
99  
2018  
2018  
2230  
美食  
100  
xiuye  
xiuye  
javascript  
xiuye