javascript 创建对象的写法

[b]第一种方法:[/b]

[i]var obj={};[/i]

example:

var so = { "name":"what?",
"action":"study & think",
"doo": function(){
console.log(this.name+" I am doing "+this.action);
}
};

so.doo(); //output: what? I am doing study & thinking

//add new function to the class
so.dee=function(){
console.log(this.name+"hwllo: I am stronger " + this.action);
}
so.dee(); //output: what? hwllo: I am stronger study & think

也可以

var so = new Object();
so = { ...} //同上

用此方式实现 Stack 类

var Stack = { "idx":0,
"store": new Array(200),
"push": function(comp){
this.store[this.idx]=comp;
this.idx++;
},
"pop": function(){
var re=this.store[this.idx-1];
this.idx--;
return re;

},
"isEmpty":function(){
if(this.idx==0) return true;
return false;
}
};

Stack.push("aaaa");
Stack.push("</definition>\n");

这个必须直接调用,不能用 new Stack(),来定义定义实例。

// 第二种方法
就好像 java 里的类与实例 ,不可以引用类(myclass)的值 ,只可以引用实例 (st1) 的值, prototype.xx 就好像是Java 里的 public ,var xxx 就是父类的私有变量, this.xxx 就是父变量,可以传递给实例


var myclass = function(){
[color=red]this[/color].name="what"; //必须用this,假如想调用初始变量值的话
var action="who do who";
var firstAction=function(){
console.log("inner class"+name);
}
}
myclass.prototype.doAction = function(name){
console.log(name+"==:)");
}
myclass.prototype.name="what name";

var st1 = new myclass();

console.log(myclass.name); //output: undefined ,
console.log(st1.name); // output: what
st1.doAction(33); // output: 33=:)


如果 已经在类中定义 this.xxx ,后面又用 prototype.xxx 定义不会生效

如 var myclass =function(){
this. name="good";
}

myclass.prototype.name="what";

var st1=new myclass();
console.log(st1.name); // good

所以定义类,要么定义一个空function(), 然后用 prototype.xx 增加属性和函数
要么全部用 this.xxx 定义, 这样就不会产生冲突
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值