My expectation from the following code would be that if I checked a.name
, it would search the prototype and return it as it was declared. Can anyone pinpoint what it is that is preventing JS from acknowledging my prototype?
var obj = function(parent){
return {
prototype: parent
}
};
var me = { name: 'keith' };
var a = new obj(me)
// => undefined
a.name
// => undefined
a.prototype.name
// => "keith"
A property named "prototype" is just a property, it does not point to the object from which the object inherits. Use Object.getPrototypeOf
or the non-standard __proto__
property to get that.
So what your function obj(me)
returns is just an object with a property "prototype" which points to an object with a property "name" which points to the string keith
. As your function returns an object, it makes no difference whether it is called with the new
keyword or not.
For inheritance, the "prototype" property of the constructor function [object] is of concern. Every object created by this constructor (which does not return an object) with the new
keyword inherits from the object to which the "prototype" property of the constructor points. So you could do this:
var Constructor = function() {
console.log(this); // logs the currently created object
// return nothing
}
Constructor.prototype = { name: 'keith' };
var a = new Constructor(); // logs an empty object
Object.getPrototypeOf(a) === Constructor.prototype; // true
a.name; // "keith" - inherited
In the function you are not touching the function prototype. You are just returning a new object with property "prototype" with parent as a value. Therefore you can only access it through that property.
It seems that you are trying to implement inheritance, here's a good read about that: Prototypal Inheritance in JavaScript and Classical Inheritance in JavaScript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With