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"
Observable.prototype= Object.prototype; Observable.prototype.forEachy = (func)=>func(); console.log(Observable.forEach(()=>"Hi, Jane"))<-- This doesn't work either.forEachyis not the same asforEach(2).forEachyis not a direct member ofObservable. It is a member of Observable's prototype. (3) Whoever instantiates from Observable will get all inherit from it's prototype indeed.new MyType(). Changing the prototype does not add new properties toMyType.