Reputation: 7136
Is there such thing as a class method in Javascript?
Example of class method in Ruby
class Item
def self.show
puts "Class method show invoked"
end
end
Item.show
Upvotes: 0
Views: 119
Reputation: 77482
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();
But better use object literal
var Item = {
show: function () {
console.log('Class method show invoked');
}
};
Item.show();
Upvotes: 3
Reputation:
There's many ways to do this, but my personal favorite is:
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())
Upvotes: 0