javascript - javascript中的构造函数如何定义静态方法?

标签 javascript static

引用: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

所以 Object 是一个构造函数,在这里我看到定义了两种类型的方法 -

  1. 静态方法 - Object.create()、Object.assign() ...
  2. 实例方法 - 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/

相关文章:

使用 SoundPool 的 OGG Audio 中的 Android Static

rust - 静态需求从何而来?

python - 如何在没有 self 的情况下访问类范围变量?

c++ - 为什么我不能在类中为静态变量设置值?

c - 文件范围内的 C 静态变量是什么意思?

javascript - Javascript 和 jQuery 中的 Trapping Function not defined 错误

javascript - 向嵌套列表类添加级别深度

javascript - 与 useEffect 一起使用时,自定义钩子(Hook)会被无限调用

javascript - 如何进行实时同步编辑?

javascript - 向 Safari 中 undefined object 原型(prototype)新添加的函数/属性