在JavaScript中以不同方式定义类之间的区别

时间:2014-05-06 23:22:24

标签: javascript

通过以下方式定义类有什么区别?

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()

由于

2 个答案:

答案 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()

更多信息: javascript : function and object...?

答案 1 :(得分:0)

如果您有什么要传递给它,通常会使用function parentCls() 例如

function parentCls(name){
    this.name=name;
    this.callMe = function (){
        alert('Method gets called');
    }
}

所以你可以创建一个像var newObject = new parentCls('abc');

这样的对象