javascript - ES6 静态方法与非静态和 ES5 OOP

标签 javascript oop ecmascript-6

我有点困惑。

如果,例如...:

function Person(firstName, lastName){
    this.firstName = firstName;
    this.lastName = lastName;
}
// so, the following will be shared, and this 
// is the best practice, right?:
Person.prototype.whatEver = function(){
    return this.firstName + " " + this.lastName;
}
// the following will also be shared, but it's 
// bad practice, because it will be included in 
// each instances and take space(memory) for nothing. correct?
Person.whatEver = function(){
    return this.firstName + " " + this.lastName;
}

如果上述正确并且我做对了,那我到底为什么需要静态函数?因为:

Person.whatEver = function(){
    return this.firstName + " " + this.lastName;
}

正是这样,对吗?

// it would need to be inside of the class, of course
static whatEver(){
    return this.firstName + " " + this.lastName;
}

最佳答案

虽然这等同于 ES6 静态方法,但它并没有按照您的想法进行:

Person.whatEver = function(){
  return this.firstName + " " + this.lastName;
}

这将 whatEver 函数放在 Person constructor 上,而不是放在实例化的 person 上 - 而 Person 构造函数可能没有 firstNamelastName。你可能在想

const person = new Person();
person.whatEver = function(){
  return this.firstName + " " + this.lastName;
}

在这种情况下,是的,每次实例化一个 Person 时运行这样的代码将导致许多函数(每个人一个),而不是原型(prototype)上的单个函数。

静态方法的使用通常与实例化对象的交互之外。想一想什么时候您可能需要与某个类关联的信息,即使还没有必要实例化任何信息。例如,您可以在 Person 类上使用静态方法:

class Person {
  static canEat() {
    return ['apples', 'bananas', 'carrots'];
  }
  // ...

关于javascript - ES6 静态方法与非静态和 ES5 OOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49549117/

相关文章:

javascript - Ext JS - 自动添加监听器

iphone - 类属性 mVar 和实例变量 self.mVar 的区别

reactjs - 使用 React、Typescript 和 ES6 进行 Jest 测试

javascript - 有人可以帮助我使用这种从某些值拆分数组的算法吗?

javascript - 如何获取JSON表的总行数?

javascript - 试图理解对象原型(prototype)

python - 如何在对象上应用连续的方法

javascript - react 属性

javascript - 在 React 中,如何将对象数组作为查询字符串传递到端点 url?

javascript - Firebase 数据库 startAt() 字符串参数长度限制?