通过以下方式定义类有什么区别?
1)
var parentCls = {
name:'John',
callMe : function (){
alert('Method gets called');
}
}
parentCls.callMe();
2)
function parentCls(){
this.name='John';
this.callMe = function (){
alert('Method gets called');
}
}
parentCls.CallMe()
由于
答案 0 :(得分:3)
这是一个对象:
var parentCls = {
name:'John',
callMe : function (){
alert('Method gets called');
}
}
parentCls.callMe();
这是一个功能:
function parentCls(){
this.name='John';
this.callMe = function (){
alert('Method gets called');
}
}
parentCls.callMe()
在此代码中,您将收到错误消息。您无法访问parentCls.callMe()
答案 1 :(得分:0)
如果您有什么要传递给它,通常会使用function parentCls()
。例如
function parentCls(name){
this.name=name;
this.callMe = function (){
alert('Method gets called');
}
}
所以你可以创建一个像var newObject = new parentCls('abc');