我有点困惑。
如果,例如...:
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
构造函数可能没有 firstName
或 lastName
。你可能在想
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/