Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Prototype Quirk - Can Anyone Explain This?

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"
like image 791
netpoetica Avatar asked Nov 12 '22 19:11

netpoetica


2 Answers

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
like image 108
Bergi Avatar answered Nov 15 '22 09:11

Bergi


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

like image 27
valentinas Avatar answered Nov 15 '22 10:11

valentinas