在类内部和外部定义JavaScript函数

时间:2019-03-17 05:19:16

标签: javascript function class

我试图弄清楚在JavaScript中定义类内部或外部函数时是否存在任何不同。 为什么我会选择一种方法呢?(请注意我的getName [在类内部]和getName2 [在类外部])。

class TestClass {
    constructor(myName) {
        this.name = myName;
    }

    getName() {
        return this.name;
    }
}

TestClass.getName2 = function() {
    //won't actually print the name variable set since not associated with an instance of the class?
    console.log(this.name);
};

var test = new TestClass("Joe");

console.log(test.getName());

///////////////

TestClass.getName2();

输出:

Joe
TestClass

到目前为止,通过此处的测试,我真正能看到的唯一区别是,我无法访问getName2中的this.name,因为我认为它与TestClass的任何实例都不相关。所以我的getName2几乎就像一个静态类函数,它不与该类的实例关联?请帮助我阐明这一点,以及为什么我会选择以一种方式实现另一种功能。

3 个答案:

答案 0 :(得分:1)

来自MDN doc

  

在ECMAScript 2015中引入的JavaScript类主要是语法糖,而不是JavaScript现有的基于原型的继承。类语法不会向JavaScript引入新的面向对象的继承模型。

所以这个...

class TestClass {
  constructor(myName) {
    this.name = myName;
  }

  getName() {
    return this.name;
  }

  static getName2() {
    return 'getName2 result';
  }
}

...与此完全等效:

const TestClass = function(myName) {
  this.name = myName;
}

TestClass.prototype.getName = function() {
  return this.name;
}

TestClass.getName2 = function() {
  return 'getName2 result';
}

因此,是使用旧的原型语法还是使用新的ES6 class语法只是个人喜好问题,并且您怀疑直接在class上定义方法等同于创建一个static class method

答案 1 :(得分:0)

我认为您没有任何理由

TestClass.getName2 = function() {

如果要使用独立功能,请将其设为独立功能。

例如

export function getName2() {...};
export TestClass;

如果要扩展现有的类,则可以这样做

TestClass.prototype.getName2 = function() {

这将允许您访问它。

答案 2 :(得分:0)

我注意到的一件事是您对对象、属性和方法使用了保留关键字。 TestClass.getName2() 应该返回 undefined,但由于您使用了“name”保留关键字。它返回类的名称,该类被视为一个对象,如函数。在您的情况下,您使用的 this.name 是指类名,它返回“TestClass”。

示例:

class TestClass {
    constructor(userName) {
        this._userName = userName;
    }

    getName() {
        return this._userName;
    }
}

TestClass.getName2 = function() {
    // returns undefined now
    console.log(this._userName);
};

var test = new TestClass("Joe");

console.log(test.getName()); // returns Joe

///////////////

TestClass.getName2(); // returns undefined
let testClassName = TestClass.name; // Just a little proof of what is returned below
console.log(testClassName); // returns TestClass

我唯一的建议是,您应该及时了解当前的保留关键字以及您可以和不可以使用它们的位置。您还可以专注于代码中的命名约定。

相关问题