Javascript中的类方法

Class method in Javascript

本文关键字:类方法 Javascript      更新时间:2023-09-26

Javascript中是否有类方法?

Ruby 中的类方法示例

class Item
  def self.show
    puts "Class method show invoked"
  end  
end
Item.show

Like So

function Item() {
   // you can put show method into function
   // Item.show = function () {};   
}
Item.show = function () {
  console.log('Class method show invoked');
}
Item.show();

但最好使用对象文字

var Item = {
  show: function () {
    console.log('Class method show invoked');
  }
};
Item.show();

有很多方法可以做到这一点,但我个人最喜欢的是:

function Person(name) { // This is the constructor
    this.name = name;
    this.alive = true;
}
Person.prototype.getName = function() {
    return this.name;
}
myHuman = new Person('Bob')
console.log(myHuman.getName())