javascript 对象的创建,引用,释放,删除方法

时间:2023-07-02 19:19:43

1。用函数构造

A.声明时同时设置属性和方法
 function func(){
  this.name = "myname";
  this.say = function(){alert("i said:")}
 }

引用时:
 var obj = new func();
 alert(obj.name);
 obj.say();

B.先声明后使用:

function func(){

}
 var obj = new func();
 obj.name = "myname";
 obj.say = function(){alert("I said:")}

引用时:
 alert(obj.name);
 obj.say();

2.用 Object:

创建和设置:
   var obj = new Object();
  obj.name = "myname";
  obj.say = function(){alert("xx")}

引用时:
  alert(obj.name);
  obj.say();

3.以json(javascript object nonation[符号]):

A.先声明,后赋值

var obj = {};
 obj.name = "myname";
 obj.say = function(){alert("i said:")}

引用:
 alert(obj.name);
 obj.say();

B.声明同时赋值:
   var obj = {name:"yourname", say:function(){alert("I say:")}}

引用时:
  alert(obj.name);
  obj.say();

手动释放对象:

对象 = null;
手动删除对象方法/属性
delete obj.name/obj.say();