Alf Moh
Alf Moh

Reputation: 7427

Function prototypes

I have a function called Observable. As per all functions, I can call certain methods on the function, that even though they do not exist directly on the function, JS moves 'down the prototypical chain' and gets the method on the function. Example of such methods is 'toString()'

function Observable(forEachy) {
  this._forEachy = forEachy;
}
console.log(Observable.toString()) // "function Observable(forEach) {this._forEach = forEach;}"

Now, when I set Observable.prototype to a new object and define some methods in that object, and call those methods on Observable, it throws an error.

Observable.prototype = {
  forEachy: function (onNext) {
    return onNext();
  }
}
    console.log(Observable.forEachy(()=>"Hi, John")) // error: Observable.forEachy is not a function

But I can call those methods on the prototype and it works just fine.

console.log(Observable.prototype.forEachy(()=>"Hi, John")); // "Hi, John"

Setting a new instance to Observable just works fine.

const abc = new Observable("HI");

console.log(abc.forEachy(()=>"Hello world")); // "Hello world"

Please, why is that?

Also, apart from passing in the argument received in the constructor to the newly created object, what else does the statement this._forEachy = forEachy do?

const abc = new Observable("HI");
console.log(abc._forEachy) // "HI"

Upvotes: 0

Views: 48

Answers (1)

Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

Your example works as expected. You should consider getting more information about Prototypes in JavaScript.

When you declare something as Function.prototype = function(){}, it works similar to methods in OOP programming. In oop you can't call Class.method(), can you? You have to first create an instance to call this method. However, keep in mind that there is a lot of differences between OOP and prototype inheritance. In reality, your "prototype" is not the abstraction. It's the existing object :)

Though, if you want to follow this way, you can create class and define static method:

class Observable {
  static forEachy(){
    // your code here
  }
}

and then:

Observable.forEachy()

Upvotes: 1

Related Questions