Object类具有方法和函数,这意味着它们都可以通过Object.nameOfMethodOrFunction()访​​问。以下问题What is the difference between a method and a function解释了方法和函数之间的区别,但没有解释如何在对象中创建它们。例如,以下代码定义了方法sayHi。但是,如何在同一个对象内定义一个函数呢?

var johnDoe =
{
      fName : 'John',
      lName: 'Doe',
      sayHi: function()
      {
        return 'Hi There';
      }
};

最佳答案

下面定义了两个类ClassAClassB,它们具有相同的功能但性质不同:

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,但显然不是一个类。

10-07 19:34
查看更多