Javascript Prototype Quirk - can anyone explain this?

My expectation from the following code will be that if I checked a.name , it will look for the prototype and return it as announced. Can anyone determine what exactly is preventing JS from recognizing 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" 
+4
source share
5 answers

A property called "prototype" is simply a property; it does not point to the object from which the object is inherited. Use Object.getPrototypeOf or the non-standard __proto__ property to get this.

What your obj(me) function returns is simply an object with the property "prototype" that points to an object with the name of the property "name" that points to the keith string. Since your function returns an object, it doesn't matter whether this is called using the new keyword or not.

For inheritance, there is a value for the "prototype" property of the constructor function [object]. Each object created by this constructor (which does not return an object) with the new keyword inherits from the object indicated by the constructor "prototype" property. So you can 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 
+1
source

In this function, you do not touch the function prototype. You simply return a new object with the "prototype" property with the parent as the value. Therefore, you can access it only through this property.

You seem to be trying to implement inheritance, read about it well here: Prototype Inheritance in JavaScript and Classical Inheritance in JavaScript

+1
source

I suspect that you are overwriting the prototype property in the same way that you can overwrite the value undefined . "

0
source

The problem is that you are returning a property called prototype with the value parent, which is the object, so you are returning a pair of prototype = {name = 'keith'} , and when you call a new obj object, you add a new property to prototype a with named prototype .

You just need to change a little, I need this is what you are trying to do. This will work, just be careful with overload properties.

 var obj = function(parent){ for(var propt in parent){ this[propt] = parent[propt]; } } var me = { name: 'keith' }; var a = new obj(me); console.log(a); // => Object { name="keith"} console.log(a.name); // => "keith" 

Edit: if you are looking for prototype inheritance, you should read this or try TypeScript , the new javascript introduced and the OO library

0
source

It seems you rewrote the real prototype fake.

-1
source

Source: https://habr.com/ru/post/1442234/


All Articles