2

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

So Object is a constructor function and here I see 2 types of methods defined -

  1. Static methods - Object.create(), Object.assign() ...
  2. Instance methods - Object.prototype.hasOwnProperty() ...

I understand how Instance methods are defined and used but no idea about static methods -

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 ?? 🤷‍♂️

Can someone please explain how to define greetStatic() ?

3
  • 2
    Person.greetStatic = function() { };? Commented Jul 16, 2021 at 21:07
  • Perhaps you should refer to these docs instead. Commented Jul 16, 2021 at 21:11
  • ok thank you. That was something silly I missed. Commented Jul 16, 2021 at 21:28

1 Answer 1

2

Static properties or methods are just properties and methods that are defined on the object itself and not the 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()) 

Using the class syntax might help make this more clear, as you can use the static keyword in it. It's just syntactic sugar and he result will be exactly the same.

class Person {
  static greetStatic() {
    return 'Static hello!';
  }
  
  greetInstance() {
    return 'Hello!';
  }
}

let p1 = new Person();
console.log(p1.greetInstance()) 
console.log(Person.greetStatic())

Sign up to request clarification or add additional context in comments.

2 Comments

yes but class being syntactic sugar is what makes it harder to understand. How do I define method on "Person" (without using class). Using dot notation? is it same as static in class?
@mustafa1993 A function is little more than an object. So setting a static function is the same as assigning a function to a property. Using the dot notation is one way to do it and a very valid one. The bracket notation Person['greetStatic'] = function () {} does exactly the same. Object.defineProperty() allows for more options to be set, but in the end has the same goal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.