下面定义了两个类ClassA
和ClassB
,具有相同的功能但性质不同:
function ClassA(name){
this.name = name;
// Defines method ClassA.say in a particular instance of ClassA
this.say = function(){
return "Hi, I am " + this.name;
}
}
function ClassB(name){
this.name = name;
}
// Defines method ClassB.say in the prototype of ClassB
ClassB.prototype.say = function(){
return "Hi, I am " + this.name;
}
如下图,它们在用法上并没有太大区别,都是“方法”。
var a = new ClassA("Alex");
alert(a.say());
var b = new ClassB("John");
alert(b.say());
所以现在你对“函数”的意思是什么,根据你作为评论给出的msdn链接,似乎“函数”只是一个“静态方法”,就像在 C# 或 Java 中一样?
// So here is a "static method", or "function"?
ClassA.createWithRandomName = function(){
return new ClassA("RandomName"); // Obviously not random, but just pretend it is.
}
var a2 = ClassA.createWithRandomName(); // Calling a "function"?
alert(a2.say()); // OK here we are still calling a method.
所以这就是你的问题:
var johnDoe =
{
fName : 'John',
lName: 'Doe',
sayHi: function()
{
return 'Hi There';
}
};
好的,这是一个Object
,但显然不是一个类。