Reputation: 1674
I'm wrapping my head about Prototype Chain under the hood but I'm having some difficulty building out a function. I want to build a function that will take in an object and add to the object's prototype. What am I doing wrong?
function getObject(obj) {
function F() {}
F.prototype.say = function(){
console.log("Hello", this.name);
}.bind(obj);
obj.prototype = Object.create(F.prototype);
return obj;
}
var r = getObject({ name: "James"});
r.name
r.say()
// r = { name: "James" }
// r.say() "Hello James"
I got what I was looking for. I was limited and wasn't allowed to use ES6 classes... I know right?
function getObject(obj) {
function F() { }
F.prototype.say = function(){
console.log("Hello", this.name);
};
const output = Object.create(F.prototype);
return Object.assign(output, obj);
}
var r = getObject({ name: "James"});
r // { name: "James" }
r.name // "James"
r.say() // "Hello James"
Upvotes: 1
Views: 202
Reputation: 215
I have modified the code. Object do not have prototype. Functions have prototype that can be used for chaining. Hope this helps.
function getObject(obj) {
function F() {}
F.prototype = Object.create(obj);
F.prototype.say = function(){
console.log("Hello", this.name);
}.bind(obj);
return new F();
}
var r = getObject({ name: "James"});
console.log(r.name); // James
r.say() // Hello James
Upvotes: 2
Reputation: 185
You are explicitly adding a prototype property on an object.obj.prototype = undefined
and when you call it with the new keyword it will just add an empty object to that property. so the new obj will be obj = {name:'james' , prototype: {}}
. Now the prototype property of the object will point to the functions F's prototype. The correct way to do this is by Object.create. You can imitate that same behaviour like this
if(!Object.create){
Object.create = function(o) {
function F() {}
F.prototype = o ;
return new F();
};
}
You can check out MDN Docs for the detailed explanation of the Object.create polyfill
Upvotes: 1
Reputation: 1407
You can add methods to an object like obj.something = function() {};
As for method chaining, you want to return this
inside your inherited function.
So something like this will answer your problem
function getObject(obj) {
obj.say = function() {
console.log(`Hello ${this.name}`);
return this;
}
obj.hi = function() {
console.log('hi');
return this;
}
return obj;
}
var newObj = getObject({});
newObj.say().hi();
// Helo A K
// hi
Also you assign obj.prototypes to equal a Class, not the class prototypes. So in the future if you want to make one prototype to equal a class prototype use obj.prototype = Object.create(anothingObj.prototype);
Upvotes: 2