引用: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
所以 Object 是一个构造函数,在这里我看到定义了两种类型的方法 -
- 静态方法 - Object.create()、Object.assign() ...
- 实例方法 - Object.prototype.hasOwnProperty() ...
我了解实例方法是如何定义和使用的,但不知道静态方法 -
function Person() { }
Person.prototype.greetInstance = function () { return 'Hello!' };
let p1 = new Person();
console.log(p1.greetInstance()) // Hello!
console.log(Person.greetStatic()) // where should I define so this works ?? 🤷♂️
有人可以解释一下如何定义greetStatic()吗?
最佳答案
静态属性或方法只是在对象本身而不是原型(prototype)上定义的属性和方法。
function Person() { }
Person.greetStatic = function() { return 'Static hello!' }
Person.prototype.greetInstance = function () { return 'Hello!' };
let p1 = new Person();
console.log(p1.greetInstance())
console.log(Person.greetStatic())
使用 class
语法可能有助于使这一点更加清晰,因为您可以在其中使用 static
关键字。这只是语法糖,结果将完全相同。
class Person {
static greetStatic() {
return 'Static hello!';
}
greetInstance() {
return 'Hello!';
}
}
let p1 = new Person();
console.log(p1.greetInstance())
console.log(Person.greetStatic())
关于javascript - javascript中的构造函数如何定义静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68415190/