I've been delving into JavaScript prototypal inheritance and the prototype property, and I decided to create a fiddle to gain a deeper understanding. However, I'm struggling to comprehend why my example isn't functioning as expected.
In the scenario below, I'm attempting to establish a hierarchy where the creation of an object reveals the name of its parent object. Despite my efforts, the logs consistently display "object".
One article clarified that prototype chaining operates in a way that if a property is absent in the object, it checks the prototype of the parent, continuing this process until reaching 'Object' and returning undefined if not found.
Feel free to check out the accompanying fiddle here: http://jsfiddle.net/hqozqd0m/
Object.prototype.cname = 'object';
function plant() {
function parentname() { return this.cname; }
return {
parentname:parentname
}
}
plant.prototype.cname = 'plant';
function tomato() {
function parentname() { return this.cname; }
return {
parentname:parentname
}
}
tomato.prototype = new plant(); // <-- setting it to plant as parent
var p = new plant();
var t = new tomato();
console.log(p.parentname()); //object
console.log(t.parentname()); //object
updated code - same result
Object.prototype.cname = 'object';
function plant() {
this.sayparentname = function() { console.log(cname); };
}
plant.prototype.cname = 'plant';
function tomato() {
this.sayparentname = function() { console.log(cname); };
}
tomato.prototype = new plant();
var p = new plant();
var t = new tomato();
p.sayparentname();
t.sayparentname();