javascript中字面量的简单总结
在很多javascript框架中经常可以看到诸如var a={};var b=[];或var c={name:"syj"};这些写法让大家摸不到头脑,由于这些写法中使用了[]{}这类字符,所以在百度中很难搜索,我就曾经尝试搜过javascript简写,但是完全不沾边。
为了让更多人少走弯路,于是决定写篇文章简单介绍下。
var a={}等同于var a=new Object;
var b=[]等同于var b=new Array;
var c={name:"syj",id:"0"};等同于
var c=new Object;
c.name="syj";
c.id="0";
这下大家明白了吧,其实这样写更加简单,而且节省空间,对javascript这种非编译型语言节省空间也很重要啊。
JavaS
对象字面量:
//只能添加静态属性和方法
var myObject={
propertyA: sha ,
propertyB: feng ,
methodA:function(){
alert(this.propertyA+ +this.propertyB);
},
methodB:function(){}
}
myObject.methodA();
//利用prototype属性可以添加公有属性和方法
function myConstructor2(){}; //声明构造函数,可以使用对象字面量语法来向prototype属性中添加所有公有成员
myConstructor2.prototype={
propertyA: sha ,
propertyB: feng ,
methodA:function(){
alert(this.propertyA+ +this.propertyB);
},
methodB:function(){}
}
var myconstrustor=new myConstructor2(); //声明对象
myconstrustor.methodA();
//只能添加静态属性和方法
var myObject={
propertyA: sha ,
propertyB: feng ,
methodA:function(){
alert(this.propertyA+ +this.propertyB);
},
methodB:function(){}
}
myObject.methodA();
//利用prototype属性可以添加公有属性和方法
function myConstructor2(){}; //声明构造函数,可以使用对象字面量语法来向prototype属性中添加所有公有成员
myConstructor2.prototype={
propertyA: sha ,
propertyB: feng ,
methodA:function(){
alert(this.propertyA+ +this.propertyB);
},
methodB:function(){}
}
var myconstrustor=new myConstructor2(); //声明对象
myconstrustor.methodA();



