在JavaScript中:类中的函数和方法定义之间的语法差异

use*_*243 5 javascript methods function

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

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

Alv*_*ong 7

以下定义了两个类,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;
}
Run Code Online (Sandbox Code Playgroud)

如下所示,它们在使用上没有太大差别,它们都是"方法".

var a = new ClassA("Alex");
alert(a.say());
var b = new ClassB("John");
alert(b.say());
Run Code Online (Sandbox Code Playgroud)

那么现在你对"函数"的意思是什么,根据你作为评论给出的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.
Run Code Online (Sandbox Code Playgroud)

这就是你在问题中的含义:

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

好的,这是一个Object,但显然不是一个类.