The prototype property and inheritance in JavaScript - javascript

The prototype property and inheritance in JavaScript is not clear to me.
I have a function:
function User (name) {
this.name = name;
}
Questions:
1) Why one of the following is false and the other is true?
User.prototype.hasOwnProperty('name'); // false
User.hasOwnProperty('name'); // true
2) What is de difference between the followings:
User.constructor;
User.prototype.constructor;
3) What happens with the User.constructor and User.prototype.constructor if I override the prototype property like this:
User.prototype = {
changeName: function(newName) {
this.name = newName;
}
};
And what if I override it like this:
User.prototype = {
constructor: User,
changeName: function(newName) {
this.name = newName;
}
};
4) Is User a function or a prototype or what? The following site refers it as prototype: 'The following example creates a prototype ...'
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor
Thank you very much for your answers.

First you need to understand what a prototype is.
In Javascript, almost everything is an object.
Edit (thanks #Mathletics):
Primitive booleans, numbers, and strings are not objects
When you create an object in Javascript, by default, its prototype will be an Object.
So, if I do:
var obj = {};
console.log(obj.__proto__)
This yields:
Object {}
Pause:
To understand the difference between obj.prototype and obj.__proto__, please, refer to this thread.
The next step is to understand the concept of prototype chaining.
This is how inheritance is structured in Javascript. Basically, a prototype is the "parent" of another object, from which it derives methods and properties.
Imagine a scheme where a Rabbit inherits from Mammal, which inherits from Animal. Representing this in Javascript prototype chain would be like:
(Rabbit) -> (Mammal) -> (Animal) -> (Object) -> null
With code:
function Animal(){}
function Mammal(){}
function Rabbit(){}
Mammal.prototype = new Animal();
Rabit.prototype = new Mammal();
If you are able to understand these concepts, you might find the answers to your questions yourself, but I'll try to make it clearer:
1) why one of the following is false and the other is true?
User.prototype.hasOwnProperty('name'); // false
User.hasOwnProperty('name'); // true
You should read the hasOwnProperty method reference:
Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object[...]
This is a way to assure that the property you are looking for is defined within the object itself, not deeper in the prototype chain.
A contrary example would be:
console.log(User.hasOwnProperty('constructor'));
Since the constructor property is defined deeper in the prototype chaing, it is not an "own property" of User object.
In your case, name is a property defined within your User object, but not defined in the context of the global Object.
2) what is de difference between the followings:
User.constructor;
User.prototype.constructor;
The fist like takes the constructor of User, the second takes the constructor of its prototype (in this case, the global Object).
3) what happens with the User.constructor and
User.prototype.constructor if I override the prototype property like
this:
User.prototype = {
changeName: function(newName) {
this.name = newName;
}
};
Please, read this thread.
TL;DR: when you assing directly to the prototype, you are breaking the prototype chain an creating a new one. In the Rabbit example, if you at some point did:
Rabbit.prototype = {
// ...
};
Your new prototype chain would be:
(Rabbit) -> (Object) -> null
So, in your first example, User.prototype.constructor would yield:
function Object{}
In your second example, it would yield:
function User(name)
Got it?
4) is User a function or a prototype or what?
User is an object whose prototype is a Function object, whose prototype is a Object object.
Drawing it:
(User) -> (Function) -> (Object) -> null
Hope I've been clear.

"Everything" in JS is an object.
So a function is a special type of object and that type of object has a property called name which is why User.hasOwnProperty("name") returns true. It has nothing to do with the property of the User object that same function can create. Try calling it something else and you will see this to be the case.
Any object derives from another object, namely it's prototype. The prototype of a function has a constructor property and __proto__ property but no name property.
So Ùser.prototype.hasOwnProperty("name")` should return false
Since all properties of the prototype are derived you can do this User.constructor even though User.hasOwnProperty("constructor") would return false

1) why one of the following is false and the other is true?
User.prototype.hasOwnProperty('name'); // false, A
User.hasOwnProperty('name'); // true, B
The prototype object hasn't been given a name property and it doesn't have one by default (as User is not native), so this is false for the prototype.
The Constructor User is a Function and you've defined the name of the function as "User". This is set on the function object when it's interpreted.
Are you sure you're not confusing this with (new User('foo')).hasOwnProperty('name'); // true?
This last case, the instance of User has a name property which is "foo", as set by the constructor User.
2) what is de difference between the followings:
User.constructor;
User.prototype.constructor;
User.constructor is Function because User is a function.
User.prototype.constructor is undefined, but you'd normally reference it back at User. This is what would later be accessed as (new User).constructor; // User
3) what happens with the User.constructor and User.prototype.constructor if I override the prototype [...]
Nothing happens to User.constructor in either case.
As for User.prototype.constructor, it wasn't define previously
so remains undefined in the first case
is set to User in the second case
Please note that in both of these cases the entire prototype is now pointing at a different Object so existing instances will not see these changes and the previous prototype chain is no longer accessible to new instances.
4) is User a function or a prototype or what?
User is a function and is a constructor. In JavaScript we call certain functions constructors if they will be used to build (construct) instances.
It may be helpful for you to see a more abstract example,
// A function `Foo` which will be our Constructor
function Foo(baz) {
this.bar = baz;
}
// notice here we have `Foo.name; // "Foo"`
// Setting up reference to the constructor through the prototype
Foo.prototype.constructor = Foo;
// Setting up reference to some other shared property through the prototype
Foo.prototype.fizz = ['buzz'];
And then usage
var foo = new Foo('hello world');
foo.bar; // "hello world" (own)
foo.fizz; // ["buzz"] (inherited)
foo.constructor; // Foo (inherited)
var bar = new Foo();
foo.fizz === bar.fizz; // true, this is the same Object reference - it is shared
Don't be afraid to try things out in your Console!

Javascript, unlike other languages (Java, ecc.), isn't class-based, it doesn't provide any way to define a class (actually, the next Javascript, ES6-Harmony, introduces the class keyword but it's just a syntactic sugar on top of prototype inheritance and, at the moment, isn't available in any browser)...
So, Javascript implements the (aka) OOP (Object Oriented Programming) via Prototype Inheritance.
If you want to create a custom object, you need to use a function that defines it. Example:
var Person = (function() {
/**
* this is the Constructor (if you have in mind a class-based language)
**/
function Person() {}
return Person;
})(window);
Doing that we have defined a New Object Person and we can have multiple instances of it using the new operator:
var me = new Person();
var you = new Person();
//...
As all languages do, javascript objects can have Methods and Properties, methods and properties can be both of Instance and Class.
var Person = (function() {
function Person() {}
/**
* Static Method
**/
Person.sayCiao = function() {};
/**
* Static Property
**/
Person.ciao = 'Ciao';
/**
* Instance Method
**/
Person.prototype.sayHello = function() {};
/**
* Instance Property
**/
Person.prototype.hello = 'Hello';
return Person;
})(window);
As you can see (try in your console), using the prototype property we can define methods or properties that all objects created by calling new Person inherit.
1) why one of the following is false and the other is true?
Of course, statics methods or properties don't belong to the instance and hasOwnProperty returns true only when is called using the constructor function. Viceversa, instances methods or properties belong only to their instances and hasOwnProperty returns true only when is called using the new operator. This is the normal behaviour that you can meet in other programming languages.
Note: in ES6 the Function Object has a property name and this is the reason how your test returns true, but isn't referenced to the name property that you define in the Person Constructor (read more).
Example of usage:
var Person = (function() {
function Person(name) {
this.firstname = name
}
Person.prototype.firstname = '';
Person.factory = function(name) {
return new Person(name);
};
return Person;
})(window);
var hitmands = Person.factory('Giuseppe');
console.log('you are', hitmands);
var you = Person.factory('BatMan');
console.log('hitmands is', you);
console.info('Person has a name?', Person.hasOwnProperty('firstname'));
console.info('You have a name?', you.hasOwnProperty('firstname'));
The property prototype belongs to the prototype chain, this is the reason how your test return false... ({}).hasOwnProperty('prototype')... You can read more following this link.
Simply prototype and what it contains doesn't is own property of your object.
2) what is de difference between the followings (ecc.)
As someone said, one belongs to the function and the other to the prototype property.
3) what happens with the User.constructor and User.prototype.constructor if I override the prototype property like this (ecc.)
You can use that way to extend behaviour from one class to another...
Read more about this.

Related

Object.getPrototypeOf vs .prototype [duplicate]

This figure again shows that every object has a prototype. Constructor
function Foo also has its own __proto__ which is Function.prototype,
and which in turn also references via its __proto__ property again to
the Object.prototype. Thus, repeat, Foo.prototype is just an explicit
property of Foo which refers to the prototype of b and c objects.
var b = new Foo(20);
var c = new Foo(30);
What are the differences between __proto__ and prototype?
The figure was taken from dmitrysoshnikov.com.
Note: there is now a 2nd edition (2017) to the above 2010 article.
__proto__ is the actual object that is used in the lookup chain to resolve methods, etc. prototype is the object that is used to build __proto__ when you create an object with new:
( new Foo ).__proto__ === Foo.prototype
( new Foo ).prototype === undefined
prototype is a property of a Function object. It is the prototype of objects constructed by that function.
__proto__ is an internal property of an object, pointing to its prototype. Current standards provide an equivalent Object.getPrototypeOf(obj) method, though the de facto standard __proto__ is quicker.
You can find instanceof relationships by comparing a function's prototype to an object's __proto__ chain, and you can break these relationships by changing prototype.
function Point(x, y) {
this.x = x;
this.y = y;
}
var myPoint = new Point();
// the following are all true
myPoint.__proto__ == Point.prototype
myPoint.__proto__.__proto__ == Object.prototype
myPoint instanceof Point;
myPoint instanceof Object;
Here Point is a constructor function, it builds an object (data structure) procedurally. myPoint is an object constructed by Point() so Point.prototype gets saved to myPoint.__proto__ at that time.
prototype property is created when a function is declared.
For instance:
function Person(dob){
this.dob = dob
};
Person.prototype property is created internally once you declare above function.
Many properties can be added to the Person.prototype which are shared by Person instances created using new Person().
// adds a new method age to the Person.prototype Object.
Person.prototype.age = function(){return date-dob};
It is worth noting that Person.prototype is an Object literal by default (it can be changed as required).
Every instance created using new Person() has a __proto__ property which points to the Person.prototype. This is the chain that is used to traverse to find a property of a particular object.
var person1 = new Person(somedate);
var person2 = new Person(somedate);
creates 2 instances of Person, these 2 objects can call age method of Person.prototype as person1.age, person2.age.
In the above picture from your question, you can see that Foo is a Function Object and therefore it has a __proto__ link to the Function.prototype which in turn is an instance of Object and has a __proto__ link to Object.prototype. The proto link ends here with __proto__ in the Object.prototype pointing to null.
Any object can have access to all the properties in its proto chain as linked by __proto__ , thus forming the basis for prototypal inheritance.
__proto__ is not a standard way of accessing the prototype chain, the standard but similar approach is to use Object.getPrototypeOf(obj).
Below code for instanceof operator gives a better understanding:
object instanceof Class operator returns true when an object is an instance of a Class, more specifically if Class.prototype is found in the proto chain of that object then the object is an instance of that Class.
function instanceOf(Func){
var obj = this;
while(obj !== null){
if(Object.getPrototypeOf(obj) === Func.prototype)
return true;
obj = Object.getPrototypeOf(obj);
}
return false;
}
The above method can be called as: instanceOf.call(object, Class) which return true if object is instance of Class.
To explain let us create a function
function a (name) {
this.name = name;
}
When JavaScript executes this code, it adds prototype property to a, prototype property is an object with two properties to it:
constructor
__proto__
So when we do
a.prototype it returns
constructor: a // function definition
__proto__: Object
Now as you can see constructor is nothing but the function a itself
and __proto__ points to the root level Object of JavaScript.
Let us see what happens when we use a function with new key word.
var b = new a ('JavaScript');
When JavaScript executes this code it does 4 things:
It creates a new object, an empty object // {}
It creates __proto__ on b and makes it point to a.prototype so b.__proto__ === a.prototype
It executes a.prototype.constructor (which is definition of function a ) with the newly created object (created in step#1) as its context (this), hence the name property passed as 'JavaScript' (which is added to this) gets added to newly created object.
It returns newly created object in (created in step#1) so var b gets assigned to newly created object.
Now if we add a.prototype.car = "BMW" and do
b.car, the output "BMW" appears.
this is because when JavaScript executed this code it searched for car property on b, it did not find then JavaScript used b.__proto__ (which was made to point to 'a.prototype' in step#2) and finds car property so return "BMW".
A nice way to think of it is...
prototype is used by constructor functions. It should've really been called something like, "prototypeToInstall", since that's what it is.
and __proto__ is that "installed prototype" on an object (that was created/installed upon the object from said constructor() function)
Prototype VS. __proto__ VS. [[Prototype]]
When creating a function, a property object called prototype is being created automatically (you didn't create it yourself) and is being attached to the function object (the constructor). Note: This new prototype object also points to, or has an internal-private link to, the native JavaScript Object.
Example:
function Foo () {
this.name = 'John Doe';
}
// Foo has an object property called prototype.
// prototype was created automatically when we declared the function Foo.
Foo.hasOwnProperty('prototype'); // true
// Now, we can assign properties and methods to it:
Foo.prototype.myName = function () {
return 'My name is ' + this.name;
}
If you create a new object out of Foo using the new keyword, you are basically creating (among other things) a new object that has an internal or private link to the function Foo's prototype we discussed earlier:
var b = new Foo();
b.[[Prototype]] === Foo.prototype // true
The private linkage to that function's object called double brackets prototype or just [[Prototype]]. Many browsers are providing us a public linkage to it that called __proto__!
To be more specific, __proto__ is actually a getter function that belong to the native JavaScript Object. It returns the internal-private prototype linkage of whatever the this binding is (returns the [[Prototype]] of b):
b.__proto__ === Foo.prototype // true
It is worth noting that starting of ECMAScript5, you can also use the getPrototypeOf method to get the internal private linkage:
Object.getPrototypeOf(b) === b.__proto__ // true
NOTE: this answer doesn't intend to cover the whole process of creating new objects or new constructors, but to help better understand what is __proto__, prototype and [[Prototype]] and how it works.
To make it a little bit clear in addition to above great answers:
function Person(name){
this.name = name
};
var eve = new Person("Eve");
eve.__proto__ == Person.prototype //true
eve.prototype //undefined
Instances have __proto__, classes have prototype.
In JavaScript, a function can be used as a constructor. That means we can create objects out of them using the new keyword. Every constructor function comes with a built-in object chained with them. This built-in object is called a prototype. Instances of a constructor function use __proto__ to access the prototype property of its constructor function.
First we created a constructor: function Foo(){}. To be clear, Foo is just another function. But we can create an object from it with the new keyword. That's why we call it the constructor function
Every function has a unique property which is called the prototype property. So, Constructor function Foo has a prototype property which points to its prototype, which is Foo.prototype (see image).
Constructor functions are themselves a function which is an instance of a system constructor called the [[Function]] constructor. So we can say that function Foo is constructed by a [[Function]] constructor. So, __proto__ of our Foo function will point to the prototype of its constructor, which is Function.prototype.
Function.prototype is itself is nothing but an object which is constructed from another system constructor called [[Object]]. So, [[Object]] is the constructor of Function.prototype. So, we can say Function.prototype is an instance of [[Object]]. So __proto__ of Function.prototype points to Object.prototype.
Object.prototype is the last man standing in the prototype chain. I mean it has not been constructed. It's already there in the system. So its __proto__ points to null.
Now we come to instances of Foo. When we create an instance using new Foo(), it creates a new object which is an instance of Foo. That means Foo is the constructor of these instances. Here we created two instances (x and y). __proto__ of x and y thus points to Foo.prototype.
I think you need to know the difference between __proto__ , [[prototype]] and prototype.
The accepted answer is helpful, but it might imply (imperfectly) that __proto__ is something only relevant to objects created using new on a constructor function, which is not true.
To be more precise: __proto__ exists on EVERY object.
But what is __proto__ at all?
Well, it is an object referencing another object which is also a property of all objects, called [[prototype]].
It's worth mentioning that [[prototype]] is something that JavaScript handles internally and is inaccessible to the developer.
Why would we need a reference object to the property [[prototype]] (of all objects)?
Because JavaScript doesn't want to allow getting / setting the [[prototype]] directly, so it allows it through a middle layer which is __proto__. So you can think of __proto__ as a getter/setter of the [[prototype]] property.
What is prototype then?
It is something specific to functions(Initially defined in Function, i.e, Function.prototype and then prototypically inherited by newly created functions, and then again those functions give it to their children, forming a chain of prototypical inheritance).
JavaScript uses a parent function's prototype to set its child functions' [[prototype]] when that parent function is run with new (remember we said all objects have [[prototype]]? well, functions are objects too, so they have [[prototype]] as well). So when the [[prototype]] of a function(child) is set to the prototype of another function(parent), you will have this in the end:
let child = new Parent();
child.__proto__ === Parent.prototype // --> true.
(Remember child.[[prototype]] is inaccessible, so we checked it using __proto__.)
Notice 1: Whenever a property is not in the child, its __proto__ will be searched "implicitly". So for instance, if child.myprop returns a value, you can't say whether "myprop" was a property of the child, or of one of its parents' prototypes. This also means that you never need to do something like: child.__proto__.__proto__.myprop on your own, just child.myprop will do that for you automatically.
Notice 2: Even if the parent's prototype has items in it, the child's own prototype will be an empty object initially. You can add items to it or remove from it manually though, if you want to further extend the inhertance chain(add child[ren] to the child). Or it can be manipulated implicitly, e.g., using the class syntax.)
Notice 3: In case you need to set/get the [[prototype]] yourself, using __proto__ is a bit outdated and modern JavaScript suggests using Object.setPrototypeOf and Object.getPrototypeOf instead.
Summary:
The __proto__ property of an object is a property that maps to the prototype of the constructor function of the object. In other words:
instance.__proto__ === constructor.prototype // true
This is used to form the prototype chain of an object. The prototype chain is a lookup mechanism for properties on an object. If an object's property is accessed, JavaScript will first look on the object itself. If the property isn't found there, it will climb all the way up to protochain until it is found (or not)
Example:
function Person (name, city) {
this.name = name;
}
Person.prototype.age = 25;
const willem = new Person('Willem');
console.log(willem.__proto__ === Person.prototype); // the __proto__ property on the instance refers to the prototype of the constructor
console.log(willem.age); // 25 doesn't find it at willem object but is present at prototype
console.log(willem.__proto__.age); // now we are directly accessing the prototype of the Person function
Our first log results to true, this is because as mentioned the __proto__ property of the instance created by the constructor refers to the prototype property of the constructor. Remember, in JavaScript, functions are also Objects. Objects can have properties, and a default property of any function is one property named prototype.
Then, when this function is utilized as a constructor function, the object instantiated from it will receive a property called __proto__. And this __proto__ property refers to the prototype property of the constructor function (which by default every function has).
Why is this useful?
JavaScript has a mechanism when looking up properties on Objects which is called 'prototypal inheritance', here is what it basically does:
First, it's checked if the property is located on the Object itself. If so, this property is returned.
If the property is not located on the object itself, it will 'climb up the protochain'. It basically looks at the object referred to by the __proto__ property. There, it checks if the property is available on the object referred to by __proto__.
If the property isn't located on the __proto__ object, it will climb up the __proto__ chain, all the way up to Object object.
If it cannot find the property anywhere on the object and its prototype chain, it will return undefined.
For example:
function Person (name) {
this.name = name;
}
let mySelf = new Person('Willem');
console.log(mySelf.__proto__ === Person.prototype);
console.log(mySelf.__proto__.__proto__ === Object.prototype);
'use strict'
function A() {}
var a = new A();
class B extends A {}
var b = new B();
console.log('====='); // =====
console.log(B.__proto__ === A); // true
console.log(B.prototype.__proto__ === A.prototype); // true
console.log(b.__proto__ === B.prototype); // true
console.log(a.__proto__ === A.prototype); // true
console.log(A.__proto__ === Function.__proto__); // true
console.log(Object.__proto__ === Function.__proto__); // true
console.log(Object.prototype === Function.__proto__.__proto__); // true
console.log(Object.prototype.__proto__ === null); // true
In JavaScript, Every object(function is object too!) has a __proto__ property, the property is reference to its prototype.
When we use the new operator with a constructor to create a new object,
the new object's __proto__ property will be set with constructor's prototype property,
then the constructor will be call by the new object,
in that process "this" will be a reference to the new object in the constructor scope, finally return the new object.
Constructor's prototype is __proto__ property, Constructor's prototype property is work with the new operator.
Constructor must be a function, but function not always is constructor even if it has prototype property.
Prototype chain actually is object's __proto__ property to reference its prototype,
and the prototype's __proto__ property to reference the prototype's prototype, and so on,
until to reference Object's prototype's __proto__ property which is reference to null.
For example:
console.log(a.constructor === A); // true
// "a" don't have constructor,
// so it reference to A.prototype by its ``__proto__`` property,
// and found constructor is reference to A
[[Prototype]] and __proto__ property actually is same thing.
We can use Object's getPrototypeOf method to get something's prototype.
console.log(Object.getPrototypeOf(a) === a.__proto__); // true
Any function we written can be use to create an object with the new operator,
so anyone of those functions can be a constructor.
I happen to be learning prototype from You Don't Know JS: this & Object Prototypes, which is a wonderful book to understand the design underneath and clarify so many misconceptions (that's why I'm trying to avoid using inheritance and things like instanceof).
But I have the same question as people asked here. Several answers are really helpful and enlightening. I'd also love to share my understandings.
What is a prototype?
Objects in JavaScript have an internal property, denoted in the specification as[[Prototype]], which is simply a reference to another object. Almost all objects are given a non-nullvalue for this property, at the time of their creation.
How to get an object's prototype?
via __proto__or Object.getPrototypeOf
var a = { name: "wendi" };
a.__proto__ === Object.prototype // true
Object.getPrototypeOf(a) === Object.prototype // true
function Foo() {};
var b = new Foo();
b.__proto__ === Foo.prototype
b.__proto__.__proto__ === Object.prototype
What is the prototype ?
prototype is an object automatically created as a special property of a function, which is used to establish the delegation (inheritance) chain, aka prototype chain.
When we create a function a, prototype is automatically created as a special property on a and saves the function code on as the constructor on prototype.
function Foo() {};
Foo.prototype // Object {constructor: function}
Foo.prototype.constructor === Foo // true
I'd love to consider this property as the place to store the properties (including methods) of a function object. That's also the reason why utility functions in JS are defined like Array.prototype.forEach() , Function.prototype.bind(), Object.prototype.toString().
Why to emphasize the property of a function?
{}.prototype // undefined;
(function(){}).prototype // Object {constructor: function}
// The example above shows object does not have the prototype property.
// But we have Object.prototype, which implies an interesting fact that
typeof Object === "function"
var obj = new Object();
So, Arary, Function, Objectare all functions. I should admit that this refreshes my impression on JS. I know functions are first-class citizen in JS but it seems that it is built on functions.
What's the difference between __proto__ and prototype?
__proto__a reference works on every object to refer to its [[Prototype]]property.
prototype is an object automatically created as a special property of a function, which is used to store the properties (including methods) of a function object.
With these two, we could mentally map out the prototype chain. Like this picture illustrates:
function Foo() {}
var b = new Foo();
b.__proto__ === Foo.prototype // true
Foo.__proto__ === Function.prototype // true
Function.prototype.__proto__ === Object.prototype // true
I know, I am late but let me try to simplify it.
Let us say there is a function
function Foo(message){
this.message = message ;
};
console.log(Foo.prototype);
Foo function will have a prototype object linked. So,Whenever we create a function in JavaScript, it always has a prototype object linked to it.
Now let us go ahead and create two objects using the function Foo.
var a = new Foo("a");
var b = new Foo("b");
console.log(a.message);
console.log(b.message);
Now we have two objects, object a and object b. Both are created
using constructor Foo. Keep in mind constructor is just a word here.
Object a and b both have a copy of message property.
These two objects a and b are linked to prototype object of constructor Foo.
On objects a and b, we can access Foo prototype using __proto__ property in all browsers and in IE we can use Object.getPrototypeOf(a) or Object.getPrototypeOf(b)
Now, Foo.prototype, a.__proto__, and b.__proto__ all denotes same object.
b.__proto__ === Object.getPrototypeOf(a);
a.__proto__ === Foo.prototype;
a.constructor.prototype === a.__proto__;
all of above would return true.
As we know, in JavaScript properties can be added dynamically. We can add property to object
Foo.prototype.Greet = function(){
console.log(this.message);
}
a.Greet();//a
b.Greet();//b
a.constructor.prototype.Greet();//undefined
As you see we added Greet() method in Foo.prototype but it is accessible in a and b or any other object which is constructed using Foo.
While executing a.Greet(), JavaScript will first search Greet in object a on property list. On not finding , it will go up in __proto__ chain of a. Since a.__proto__ and Foo.prototype is same object, JavaScript will find Greet() method and execute it.
I hope, now prototype and __proto__ is simplified a bit.
Another good way to understand it:
var foo = {}
/*
foo.constructor is Object, so foo.constructor.prototype is actually
Object.prototype; Object.prototype in return is what foo.__proto__ links to.
*/
console.log(foo.constructor.prototype === foo.__proto__);
// this proves what the above comment proclaims: Both statements evaluate to true.
console.log(foo.__proto__ === Object.prototype);
console.log(foo.constructor.prototype === Object.prototype);
Only after IE11 __proto__ is supported. Before that version, such as IE9, you could use the constructor to get the __proto__.
prototype
prototype is a property of a Function. It is the blueprint for creating objects by using that (constructor) function with new keyword.
__proto__
__proto__ is used in the lookup chain to resolve methods, properties. when an object is created (using constructor function with new keyword), __proto__ is set to (Constructor) Function.prototype
function Robot(name) {
this.name = name;
}
var robot = new Robot();
// the following are true
robot.__proto__ == Robot.prototype
robot.__proto__.__proto__ == Object.prototype
Here is my (imaginary) explanation to clear the confusion:
Imagine there is an imaginary class (blueprint/coockie cutter) associated with function. That imaginary class is used to instantiate objects. prototype is the extention mechanism (extention method in C#, or Swift Extension) to add things to that imaginary class.
function Robot(name) {
this.name = name;
}
The above can be imagined as:
// imaginary class
class Robot extends Object{
static prototype = Robot.class
// Robot.prototype is the way to add things to Robot class
// since Robot extends Object, therefore Robot.prototype.__proto__ == Object.prototype
var __proto__;
var name = "";
// constructor
function Robot(name) {
this.__proto__ = prototype;
prototype = undefined;
this.name = name;
}
}
So,
var robot = new Robot();
robot.__proto__ == Robot.prototype
robot.prototype == undefined
robot.__proto__.__proto__ == Object.prototype
Now adding method to the prototype of Robot:
Robot.prototype.move(x, y) = function(x, y){ Robot.position.x = x; Robot.position.y = y};
// Robot.prototype.move(x, y) ===(imagining)===> Robot.class.move(x, y)
The above can be imagined as extension of Robot class:
// Swift way of extention
extension Robot{
function move(x, y){
Robot.position.x = x; Robot.position.y = y
}
}
Which in turn,
// imaginary class
class Robot{
static prototype = Robot.class // Robot.prototype way to extend Robot class
var __proto__;
var name = "";
// constructor
function Robot(name) {
this.__proto__ = prototype;
prototype = undefined;
this.name = name;
}
// added by prototype (as like C# extension method)
function move(x, y){
Robot.position.x = x; Robot.position.y = y
};
}
I've made for myself a small drawing that represents the following code snippet:
var Cat = function() {}
var tom = new Cat()
I have a classical OO background, so it was helpful to represent the hierarchy in this manner. To help you read this diagram, treat the rectangles in the image as JavaScript objects. And yes, functions are also objects. ;)
Objects in JavaScript have properties and __proto__ is just one of them.
The idea behind this property is to point to the ancestor object in the (inheritance) hierarchy.
The root object in JavaScript is Object.prototype and all other objects are descendants of this one. The __proto__ property of the root object is null, which represents the end of inheritance chain.
You'll notice that prototype is a property of functions. Cat is a function, but also Function and Object are (native) functions. tom is not a function, thus it does not have this property.
The idea behind this property is to point to an object which will be used in the construction, i.e. when you call the new operator on that function.
Note that prototype objects (yellow rectangles) have another property called
constructor which points back to the respective function object. For
brevity reasons this was not depicted.
Indeed, when we create the tom object with new Cat(), the created object will have the __proto__ property set to the prototype object of the constructor function.
In the end, let us play with this diagram a bit. The following statements are true:
tom.__proto__ property points to the same object as Cat.prototype.
Cat.__proto__ points to the Function.prototype object, just like Function.__proto__ and Object.__proto__ do.
Cat.prototype.__proto__ and tom.__proto__.__proto__ point to the same object and that is Object.prototype.
Cheers!
[[Prototype]] :
[[Prototype]] is an internal hidden property of objects in JS and it is a reference to another object. Every object at the time of creation receives a non-null value for [[Prototype]]. Remember [[Get]] operation is invoked when we reference a property on an object like, myObject.a. If the object itself has a property, a on it then that property will be used.
let myObject= {
a: 2
};
console.log(myObject.a); // 2
But if the object itself directly does not have the requested property then [[Get]] operation will proceed to follow the [[Prototype]] link of the object. This process will continue until either a matching property name is found or the [[Prototype]] chain ends(at the built-in Object.prototype). If no matching property is found then undefined will be returned. Object.create(specifiedObject) creates an object with the [[Prototype]] linkage to the specified object.
let anotherObject= {
a: 2
};
// create an object linked to anotherObject
let myObject= Object.create(anotherObject);
console.log(myObject.a); // 2
Both for..in loop and in operator use [[Prototype]] chain lookup process. So if we use for..in loop to iterate over the properties of an object then all the enumerable properties which can be reached via that object's [[Prototype]] chain also will be enumerated along with the enumerable properties of the object itself. And when using in operator to test for the existence of a property on an object then in operator will check all the properties via [[Prototype]] linkage of the object regardless of their enumerability.
// for..in loop uses [[Prototype]] chain lookup process
let anotherObject= {
a: 2
};
let myObject= Object.create(anotherObject);
for(let k in myObject) {
console.log("found: " + k); // found: a
}
// in operator uses [[Prototype]] chain lookup process
console.log("a" in myObject); // true
.prototype :
.prototype is a property of functions in JS and it refers to an object having constructor property which stores all the properties(and methods) of the function object.
let foo= function(){}
console.log(foo.prototype);
// returns {constructor: f} object which now contains all the default properties
foo.id= "Walter White";
foo.job= "teacher";
console.log(foo.prototype);
// returns {constructor: f} object which now contains all the default properties and 2 more properties that we added to the fn object
/*
{constructor: f}
constructor: f()
id: "Walter White"
job: "teacher"
arguments: null
caller: null
length: 0
name: "foo"
prototype: {constructor: f}
__proto__: f()
[[FunctionLocation]]: VM789:1
[[Scopes]]: Scopes[2]
__proto__: Object
*/
But normal objects in JS does not have .prototype property. We know Object.prototype is the root object of all the objects in JS. So clearly Object is a function i.e. typeof Object === "function" . That means we also can create object from the Object function like, let myObj= new Object( ). Similarly Array, Function are also functions so we can use Array.prototype, Function.prototype to store all the generic properties of arrays and functions. So we can say JS is built on functions.
{}.prototype; // SyntaxError: Unexpected token '.'
(function(){}).prototype; // {constructor: f}
Also using new operator if we create objects from a function then internal hidden [[Prototype]] property of those newly created objects will point to the object referenced by the .prototype property of the original function. In the below code, we have created an object, a from a fn, Letter and added 2 properties one to the fn object and another to the prototype object of the fn. Now if we try to access both of the properties on the newly created object, a then we only will be able to access the property added to the prototype object of the function. This is because the prototype object of the function is now on the [[Prototype]] chain of the newly created object, a.
let Letter= function(){}
let a= new Letter();
Letter.from= "Albuquerque";
Letter.prototype.to= "New Hampshire";
console.log(a.from); // undefined
console.log(a.to); // New Hampshire
.__proto__ :
.__proto__ is a property of objects in JS and it references the another object in the [[Prototype]] chain. We know [[Prototype]] is an internal hidden property of objects in JS and it references another object in the [[Prototype]] chain. We can get or set the object referred by the internal [[Prototype]] property in 2 ways
Object.getPrototypeOf(obj) / Object.setPrototypeOf(obj)
obj.__proto__
We can traverse the [[Prototype]] chain using: .__proto__.__proto__. . . Along with .constructor, .toString( ), .isPrototypeOf( ) our dunder proto property (__proto__) actually exists on the built-in Object.prototype root object, but available on any particular object. Our .__proto__ is actually a getter/setter. Implementation of .__proto__ in Object.prototype is as below :
Object.defineProperty(Object.prototype, "__proto__", {
get: function() {
return Object.getPrototypeOf(this);
},
set: function(o) {
Object.setPrototypeOf(this, o);
return o;
}
});
To retrieve the value of obj.__proto__ is like calling, obj.__proto__() which actually returns the calling of the getter fn, Object.getPrototypeOf(obj) which exists on Object.prototype object. Although .__proto__ is a settable property but we should not change [[Prototype]] of an already existing object because of performance issues.
Using new operator if we create objects from a function then internal hidden [[Prototype]] property of those newly created objects will point to the object referenced by the .prototype property of the original function. Using .__proto__ property we can access the other object referenced by internal hidden [[Prototype]] property of the object. But __proto__ is not the same as [[Prototype]] rather a getter/setter for it. Consider below code :
let Letter= function() {}
let a= new Letter();
let b= new Letter();
let z= new Letter();
// output in console
a.__proto__ === Letter.prototype; // true
b.__proto__ === Letter.prototype; // true
z.__proto__ === Letter.prototype; // true
Letter.__proto__ === Function.prototype; // true
Function.prototype.__proto__ === Object.prototype; // true
Letter.prototype.__proto__ === Object.prototype; // true
To put it simply:
> var a = 1
undefined
> a.__proto__
[Number: 0]
> Number.prototype
[Number: 0]
> Number.prototype === a.__proto__
true
This allows you to attach properties to X.prototype AFTER objects of type X has been instantiated, and they will still get access to those new properties through the __proto__ reference which the Javascript-engine uses to walk up the prototype chain.
Prototype or Object.prototype is a property of an object literal. It represents the Object prototype object which you can override to add more properties or methods further along the prototype chain.
__proto__ is an accessor property (get and set function) that exposes the internal prototype of an object thru which it is accessed.
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
http://www.w3schools.com/js/js_object_prototypes.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
Explanatory example:
function Dog(){}
Dog.prototype.bark = "woof"
let myPuppie = new Dog()
now, myPupppie has __proto__ property which points to Dog.prototype.
> myPuppie.__proto__
>> {bark: "woof", constructor: ƒ}
but myPuppie does NOT have a prototype property.
> myPuppie.prototype
>> undefined
So, __proto__ of mypuppie is the reference to the .prototype property of constructor function that was used to instantiate this object (and the current myPuppie object has "delegates to" relationship to this __proto__ object), while .prototype property of myPuppie is simply absent (since we did not set it).
Good explanation by MPJ here:
proto vs prototype - Object Creation in JavaScript
DEFINITIONS
(number inside the parenthesis () is a 'link' to the code that is written below)
prototype - an object that consists of:
=> functions (3) of this
particular ConstructorFunction.prototype(5) that are accessible by each
object (4) created or to-be-created through this constructor function (1)
=> the constructor function itself (1)
=> __proto__ of this particular object (prototype object)
__proto__ (dandor proto?) - a link BETWEEN any object (2) created through a particular constructor function (1), AND the prototype object's properties (5) of that constructor THAT allows each created object (2) to have access to the prototype's functions and methods (4) (__proto__ is by default included in every single object in JS)
CODE CLARIFICATION
1.
function Person (name, age) {
this.name = name;
this.age = age;
}
2.
var John = new Person(‘John’, 37);
// John is an object
3.
Person.prototype.getOlder = function() {
this.age++;
}
// getOlder is a key that has a value of the function
4.
John.getOlder();
5.
Person.prototype;
I'll try a 4th grade explanation:
Things are very simple. A prototype is an example of how something should be built. So:
I'm a function and I build new objects similar to my prototype
I'm an object and I was built using my __proto__ as an example
proof:
function Foo() { }
var bar = new Foo()
// `bar` is constructed from how Foo knows to construct objects
bar.__proto__ === Foo.prototype // => true
// bar is an instance - it does not know how to create objects
bar.prototype // => undefined
Every function you create has a property called prototype, and it starts off its life as an empty object. This property is of no use until you use this function as constructor function i.e. with the 'new' keyword.
This is often confused with the __proto__ property of an object. Some might get confused and except that the prototype property of an object might get them the proto of an object. But this is not case. prototype is used to get the __proto__ of an object created from a function constructor.
In the above example:
function Person(name){
this.name = name
};
var eve = new Person("Eve");
console.log(eve.__proto__ == Person.prototype) // true
// this is exactly what prototype does, made Person.prototype equal to eve.__proto__
I hope it makes sense.
What about using __proto__ for static methods?
function Foo(name){
this.name = name
Foo.__proto__.collection.push(this)
Foo.__proto__.count++
}
Foo.__proto__.count=0
Foo.__proto__.collection=[]
var bar = new Foo('bar')
var baz = new Foo('baz')
Foo.count;//2
Foo.collection // [{...}, {...}]
bar.count // undefined
(function(){
let a = function(){console.log(this.b)};
a.prototype.b = 1;
a.__proto__.b = 2;
let q = new a();
console.log(a.b);
console.log(q.b)
})()
Try this code to understand
There is only one object that is used for protypal chaining. This object obviously has a name and a value: __proto__ is its name, and prototype is its value. That's all.
to make it even easier to grasp, look at the diagram on the top of this post (Diagram by dmitry soshnikov), you'll never find __proto__ points to something else other than prototype as its value.
The gist is this: __proto__ is the name that references the prototypal object, and prototype is the actual prototypal object.
It's like saying:
let x = {name: 'john'};
x is the object name (pointer), and {name: 'john'} is the actual object (data value).
NOTE: this just a massively simplified hint on how they are related on a high level.
Update: Here is a simple concrete javascript example for better illustration:
let x = new String("testing") // Or any other javascript object you want to create
Object.getPrototypeOf(x) === x.__proto__; // true
This means that when Object.getPrototypeOf(x) gets us the actual value of x (which is its prototype), is exactly what the __proto__ of x is pointing to. Therefore __proto__ is indeed pointing to the prototype of x. Thus __proto__ references x (pointer of x), and prototype is the value of x (its prototype).
I hope it's a bit clear now.
so many good answers exist for this question, but for recap and compact form of answer that have good details I add the following:
the first thing that we must consider is when JS was invented, computers have very low memory, so if we need a process for creating new object types, we must consider memory performance.
so they located methods that object created from that specific object type need, on the separate part of memory instead of every time we create a new object, store methods besides the object.
so if we reinvent the new operator and constructor function concept with JS's new features we have these steps:
and empty object. (that will be the final result of instantiation of object type)
let empty={}
we already know that for memory performance reasons all the methods that are needed for instances of an object type are located on the constructor function's prototype property. (functions are also objects so they can have properties)
so we reference the empty object's __protp__ to the location where those methods exist.
(we consider the function that we use conceptually as the constructor, named constructor.
empty.__proto__ = constructor.prototype
we must initialize object type values.
in JS function are disconnected from objects. with dot notation or methods like bind call apply that function objects have we must tell "what is the this context of the function".
let newFunc = constructor.bind(empty)
now we have a new function that has an empty object as this context.
after execution of this function. the empty object will be filled, and the result of instantiation of type object will be this empty object if defined constructor function doesn't return(as if that will be the result of the process)
so as you see __proto__ is a property of objects that refers to other objects(in JS functions are also object) prototype object property which consisted of properties that use across instances of a specific object type.
as you can guess from the phrase, functions are objects, functions also have __proto__ property so they can refer to other object's prototype properties. this is how prototype inheritance is implemented.
my understanding is: __proto__ and prototype are all served for the prototype chain technique . the difference is functions named with underscore(like __proto__) are not aim for developers invoked explicitly at all. in other words, they are just for some mechanisms like inherit etc. they are 'back-end'. but functions named without underscore are designed for invoked explicitly, they are 'front-end'.
__proto__ is the base to construct prototype and a constructor function eg: function human(){} has prototype which is shared via __proto__ in the new instance of the constructor function. A more detailed read here
As this rightly stated
__proto__ is the actual object that is used in the lookup chain to
resolve methods, etc. prototype is the object that is used to build
__proto__ when you create an object with new:
( new Foo ).__proto__ === Foo.prototype;
( new Foo ).prototype === undefined;
We can further note that __proto__ property of an object created using function constructor points towards the memory location pointed towards by prototype property of that respective constructor.
If we change the memory location of prototype of constructor function, __proto__ of derived object will still continue to point towards the original address space. Therefore to make common property available down the inheritance chain, always append property to constructor function prototype, instead of re-initializing it (which would change its memory address).
Consider the following example:
function Human(){
this.speed = 25;
}
var himansh = new Human();
Human.prototype.showSpeed = function(){
return this.speed;
}
himansh.__proto__ === Human.prototype; //true
himansh.showSpeed(); //25
//now re-initialzing the Human.prototype aka changing its memory location
Human.prototype = {lhs: 2, rhs:3}
//himansh.__proto__ will still continue to point towards the same original memory location.
himansh.__proto__ === Human.prototype; //false
himansh.showSpeed(); //25

How function resolution in prototype chain will work for Object.prototype as constructor

I am referring to this web archive of an article originally on Helephant.com, to learn how Javascript resolves functions in the prototype chain when called on objects.
The article quotes,
If the object doesn’t have the method set directly on it, javascript then looks for a Constructor function that created the object. Javascript checks the constructor’s prototype property for the method.
In the following code, if you check rufus.constructor is the global Object() constructor, so will JS directly check the global Object() since rufus.constructor is Object() or as per the article quote above it will first look at the constructor and then find the prototype property and so on.. How will JS resolve the function (rufus.toString). I am quite confused with this.
//PET CONSTRUCTOR
function Pet(name, species, hello)
{ this.name = name;
this.species = species;
this.hello = hello; }
Pet.prototype = {
sayHello : function(){
alert(this.hello);
}
}
//CAT CONSTRUCTOR
function Cat(name, hello, breed, whiskerLength)
{ this.name = name;
this.hello = hello;
this.breed = breed;
this.whiskerLength = whiskerLength;}
Cat.prototype = new Pet();
var rufus = new Cat("rufus", "miaow", "Maine Coon", 7);
rufus.toString;
If the object doesn’t have the method set directly on it, javascript
then looks for a Constructor function that created the object.
Javascript checks the constructor’s prototype property for the method.
The wording is confusing. The JavaScript looks up the prototype chain through __proto__ and does not use constructor property. They mentioned Constructor because usually, that is how objects get their prototype - through Constructor.prototype property. But that is not always true. You can set the prototype like this:
var rufus2 = Object.create(new Pet());
Object.getPrototypeOf(rufus) === Object.getPrototypeOf(rufus2); // true
Regarding how the toString method is resolved:
rufus.hasOwnProperty('toString'); // false -> go up
(new Pet()) rufus.__proto__.hasOwnProperty('toString'); // false -> go up
({sayHello :...}) rufus.__proto__.__proto__.hasOwnProperty('toString'); // false -> go up
(Object.prototype) rufus.__proto__.__proto__.__proto__.hasOwnProperty('toString'); // true
function Person () { }
Person.prototype.sayName = function () { };
var bob = new Person();
console.log(bob.sayName === Person.prototype.sayName); // true
console.log(bob.constructor.prototype.sayName === Person.prototype.sayName); // true
console.log(bob.__proto__.sayName === Person.prototype.sayName); // true
console.log(bob.constructor === Person); // true
console.log(bob.__proto__ === Person.prototype); // true
Those are your relationships.
If a property / function can not be found on an object, it goes up the __proto__ chain to find what it's looking for. In older browsers, __proto__ was not accessible to JS devs, but was still the object that the browser/Node used behind the scenes, to refer to the Constructor.prototype property.
PS: try not to use deep hierarchy in JS. That is a path of many tears. Deep hierarchies cause pain in other class-based languages, but are misery in JS, where often a function would suffice.

Create Object with another Object as its Prototype in Javascript [duplicate]

This figure again shows that every object has a prototype. Constructor
function Foo also has its own __proto__ which is Function.prototype,
and which in turn also references via its __proto__ property again to
the Object.prototype. Thus, repeat, Foo.prototype is just an explicit
property of Foo which refers to the prototype of b and c objects.
var b = new Foo(20);
var c = new Foo(30);
What are the differences between __proto__ and prototype?
The figure was taken from dmitrysoshnikov.com.
Note: there is now a 2nd edition (2017) to the above 2010 article.
__proto__ is the actual object that is used in the lookup chain to resolve methods, etc. prototype is the object that is used to build __proto__ when you create an object with new:
( new Foo ).__proto__ === Foo.prototype
( new Foo ).prototype === undefined
prototype is a property of a Function object. It is the prototype of objects constructed by that function.
__proto__ is an internal property of an object, pointing to its prototype. Current standards provide an equivalent Object.getPrototypeOf(obj) method, though the de facto standard __proto__ is quicker.
You can find instanceof relationships by comparing a function's prototype to an object's __proto__ chain, and you can break these relationships by changing prototype.
function Point(x, y) {
this.x = x;
this.y = y;
}
var myPoint = new Point();
// the following are all true
myPoint.__proto__ == Point.prototype
myPoint.__proto__.__proto__ == Object.prototype
myPoint instanceof Point;
myPoint instanceof Object;
Here Point is a constructor function, it builds an object (data structure) procedurally. myPoint is an object constructed by Point() so Point.prototype gets saved to myPoint.__proto__ at that time.
prototype property is created when a function is declared.
For instance:
function Person(dob){
this.dob = dob
};
Person.prototype property is created internally once you declare above function.
Many properties can be added to the Person.prototype which are shared by Person instances created using new Person().
// adds a new method age to the Person.prototype Object.
Person.prototype.age = function(){return date-dob};
It is worth noting that Person.prototype is an Object literal by default (it can be changed as required).
Every instance created using new Person() has a __proto__ property which points to the Person.prototype. This is the chain that is used to traverse to find a property of a particular object.
var person1 = new Person(somedate);
var person2 = new Person(somedate);
creates 2 instances of Person, these 2 objects can call age method of Person.prototype as person1.age, person2.age.
In the above picture from your question, you can see that Foo is a Function Object and therefore it has a __proto__ link to the Function.prototype which in turn is an instance of Object and has a __proto__ link to Object.prototype. The proto link ends here with __proto__ in the Object.prototype pointing to null.
Any object can have access to all the properties in its proto chain as linked by __proto__ , thus forming the basis for prototypal inheritance.
__proto__ is not a standard way of accessing the prototype chain, the standard but similar approach is to use Object.getPrototypeOf(obj).
Below code for instanceof operator gives a better understanding:
object instanceof Class operator returns true when an object is an instance of a Class, more specifically if Class.prototype is found in the proto chain of that object then the object is an instance of that Class.
function instanceOf(Func){
var obj = this;
while(obj !== null){
if(Object.getPrototypeOf(obj) === Func.prototype)
return true;
obj = Object.getPrototypeOf(obj);
}
return false;
}
The above method can be called as: instanceOf.call(object, Class) which return true if object is instance of Class.
To explain let us create a function
function a (name) {
this.name = name;
}
When JavaScript executes this code, it adds prototype property to a, prototype property is an object with two properties to it:
constructor
__proto__
So when we do
a.prototype it returns
constructor: a // function definition
__proto__: Object
Now as you can see constructor is nothing but the function a itself
and __proto__ points to the root level Object of JavaScript.
Let us see what happens when we use a function with new key word.
var b = new a ('JavaScript');
When JavaScript executes this code it does 4 things:
It creates a new object, an empty object // {}
It creates __proto__ on b and makes it point to a.prototype so b.__proto__ === a.prototype
It executes a.prototype.constructor (which is definition of function a ) with the newly created object (created in step#1) as its context (this), hence the name property passed as 'JavaScript' (which is added to this) gets added to newly created object.
It returns newly created object in (created in step#1) so var b gets assigned to newly created object.
Now if we add a.prototype.car = "BMW" and do
b.car, the output "BMW" appears.
this is because when JavaScript executed this code it searched for car property on b, it did not find then JavaScript used b.__proto__ (which was made to point to 'a.prototype' in step#2) and finds car property so return "BMW".
A nice way to think of it is...
prototype is used by constructor functions. It should've really been called something like, "prototypeToInstall", since that's what it is.
and __proto__ is that "installed prototype" on an object (that was created/installed upon the object from said constructor() function)
Prototype VS. __proto__ VS. [[Prototype]]
When creating a function, a property object called prototype is being created automatically (you didn't create it yourself) and is being attached to the function object (the constructor). Note: This new prototype object also points to, or has an internal-private link to, the native JavaScript Object.
Example:
function Foo () {
this.name = 'John Doe';
}
// Foo has an object property called prototype.
// prototype was created automatically when we declared the function Foo.
Foo.hasOwnProperty('prototype'); // true
// Now, we can assign properties and methods to it:
Foo.prototype.myName = function () {
return 'My name is ' + this.name;
}
If you create a new object out of Foo using the new keyword, you are basically creating (among other things) a new object that has an internal or private link to the function Foo's prototype we discussed earlier:
var b = new Foo();
b.[[Prototype]] === Foo.prototype // true
The private linkage to that function's object called double brackets prototype or just [[Prototype]]. Many browsers are providing us a public linkage to it that called __proto__!
To be more specific, __proto__ is actually a getter function that belong to the native JavaScript Object. It returns the internal-private prototype linkage of whatever the this binding is (returns the [[Prototype]] of b):
b.__proto__ === Foo.prototype // true
It is worth noting that starting of ECMAScript5, you can also use the getPrototypeOf method to get the internal private linkage:
Object.getPrototypeOf(b) === b.__proto__ // true
NOTE: this answer doesn't intend to cover the whole process of creating new objects or new constructors, but to help better understand what is __proto__, prototype and [[Prototype]] and how it works.
To make it a little bit clear in addition to above great answers:
function Person(name){
this.name = name
};
var eve = new Person("Eve");
eve.__proto__ == Person.prototype //true
eve.prototype //undefined
Instances have __proto__, classes have prototype.
In JavaScript, a function can be used as a constructor. That means we can create objects out of them using the new keyword. Every constructor function comes with a built-in object chained with them. This built-in object is called a prototype. Instances of a constructor function use __proto__ to access the prototype property of its constructor function.
First we created a constructor: function Foo(){}. To be clear, Foo is just another function. But we can create an object from it with the new keyword. That's why we call it the constructor function
Every function has a unique property which is called the prototype property. So, Constructor function Foo has a prototype property which points to its prototype, which is Foo.prototype (see image).
Constructor functions are themselves a function which is an instance of a system constructor called the [[Function]] constructor. So we can say that function Foo is constructed by a [[Function]] constructor. So, __proto__ of our Foo function will point to the prototype of its constructor, which is Function.prototype.
Function.prototype is itself is nothing but an object which is constructed from another system constructor called [[Object]]. So, [[Object]] is the constructor of Function.prototype. So, we can say Function.prototype is an instance of [[Object]]. So __proto__ of Function.prototype points to Object.prototype.
Object.prototype is the last man standing in the prototype chain. I mean it has not been constructed. It's already there in the system. So its __proto__ points to null.
Now we come to instances of Foo. When we create an instance using new Foo(), it creates a new object which is an instance of Foo. That means Foo is the constructor of these instances. Here we created two instances (x and y). __proto__ of x and y thus points to Foo.prototype.
I think you need to know the difference between __proto__ , [[prototype]] and prototype.
The accepted answer is helpful, but it might imply (imperfectly) that __proto__ is something only relevant to objects created using new on a constructor function, which is not true.
To be more precise: __proto__ exists on EVERY object.
But what is __proto__ at all?
Well, it is an object referencing another object which is also a property of all objects, called [[prototype]].
It's worth mentioning that [[prototype]] is something that JavaScript handles internally and is inaccessible to the developer.
Why would we need a reference object to the property [[prototype]] (of all objects)?
Because JavaScript doesn't want to allow getting / setting the [[prototype]] directly, so it allows it through a middle layer which is __proto__. So you can think of __proto__ as a getter/setter of the [[prototype]] property.
What is prototype then?
It is something specific to functions(Initially defined in Function, i.e, Function.prototype and then prototypically inherited by newly created functions, and then again those functions give it to their children, forming a chain of prototypical inheritance).
JavaScript uses a parent function's prototype to set its child functions' [[prototype]] when that parent function is run with new (remember we said all objects have [[prototype]]? well, functions are objects too, so they have [[prototype]] as well). So when the [[prototype]] of a function(child) is set to the prototype of another function(parent), you will have this in the end:
let child = new Parent();
child.__proto__ === Parent.prototype // --> true.
(Remember child.[[prototype]] is inaccessible, so we checked it using __proto__.)
Notice 1: Whenever a property is not in the child, its __proto__ will be searched "implicitly". So for instance, if child.myprop returns a value, you can't say whether "myprop" was a property of the child, or of one of its parents' prototypes. This also means that you never need to do something like: child.__proto__.__proto__.myprop on your own, just child.myprop will do that for you automatically.
Notice 2: Even if the parent's prototype has items in it, the child's own prototype will be an empty object initially. You can add items to it or remove from it manually though, if you want to further extend the inhertance chain(add child[ren] to the child). Or it can be manipulated implicitly, e.g., using the class syntax.)
Notice 3: In case you need to set/get the [[prototype]] yourself, using __proto__ is a bit outdated and modern JavaScript suggests using Object.setPrototypeOf and Object.getPrototypeOf instead.
Summary:
The __proto__ property of an object is a property that maps to the prototype of the constructor function of the object. In other words:
instance.__proto__ === constructor.prototype // true
This is used to form the prototype chain of an object. The prototype chain is a lookup mechanism for properties on an object. If an object's property is accessed, JavaScript will first look on the object itself. If the property isn't found there, it will climb all the way up to protochain until it is found (or not)
Example:
function Person (name, city) {
this.name = name;
}
Person.prototype.age = 25;
const willem = new Person('Willem');
console.log(willem.__proto__ === Person.prototype); // the __proto__ property on the instance refers to the prototype of the constructor
console.log(willem.age); // 25 doesn't find it at willem object but is present at prototype
console.log(willem.__proto__.age); // now we are directly accessing the prototype of the Person function
Our first log results to true, this is because as mentioned the __proto__ property of the instance created by the constructor refers to the prototype property of the constructor. Remember, in JavaScript, functions are also Objects. Objects can have properties, and a default property of any function is one property named prototype.
Then, when this function is utilized as a constructor function, the object instantiated from it will receive a property called __proto__. And this __proto__ property refers to the prototype property of the constructor function (which by default every function has).
Why is this useful?
JavaScript has a mechanism when looking up properties on Objects which is called 'prototypal inheritance', here is what it basically does:
First, it's checked if the property is located on the Object itself. If so, this property is returned.
If the property is not located on the object itself, it will 'climb up the protochain'. It basically looks at the object referred to by the __proto__ property. There, it checks if the property is available on the object referred to by __proto__.
If the property isn't located on the __proto__ object, it will climb up the __proto__ chain, all the way up to Object object.
If it cannot find the property anywhere on the object and its prototype chain, it will return undefined.
For example:
function Person (name) {
this.name = name;
}
let mySelf = new Person('Willem');
console.log(mySelf.__proto__ === Person.prototype);
console.log(mySelf.__proto__.__proto__ === Object.prototype);
'use strict'
function A() {}
var a = new A();
class B extends A {}
var b = new B();
console.log('====='); // =====
console.log(B.__proto__ === A); // true
console.log(B.prototype.__proto__ === A.prototype); // true
console.log(b.__proto__ === B.prototype); // true
console.log(a.__proto__ === A.prototype); // true
console.log(A.__proto__ === Function.__proto__); // true
console.log(Object.__proto__ === Function.__proto__); // true
console.log(Object.prototype === Function.__proto__.__proto__); // true
console.log(Object.prototype.__proto__ === null); // true
In JavaScript, Every object(function is object too!) has a __proto__ property, the property is reference to its prototype.
When we use the new operator with a constructor to create a new object,
the new object's __proto__ property will be set with constructor's prototype property,
then the constructor will be call by the new object,
in that process "this" will be a reference to the new object in the constructor scope, finally return the new object.
Constructor's prototype is __proto__ property, Constructor's prototype property is work with the new operator.
Constructor must be a function, but function not always is constructor even if it has prototype property.
Prototype chain actually is object's __proto__ property to reference its prototype,
and the prototype's __proto__ property to reference the prototype's prototype, and so on,
until to reference Object's prototype's __proto__ property which is reference to null.
For example:
console.log(a.constructor === A); // true
// "a" don't have constructor,
// so it reference to A.prototype by its ``__proto__`` property,
// and found constructor is reference to A
[[Prototype]] and __proto__ property actually is same thing.
We can use Object's getPrototypeOf method to get something's prototype.
console.log(Object.getPrototypeOf(a) === a.__proto__); // true
Any function we written can be use to create an object with the new operator,
so anyone of those functions can be a constructor.
I happen to be learning prototype from You Don't Know JS: this & Object Prototypes, which is a wonderful book to understand the design underneath and clarify so many misconceptions (that's why I'm trying to avoid using inheritance and things like instanceof).
But I have the same question as people asked here. Several answers are really helpful and enlightening. I'd also love to share my understandings.
What is a prototype?
Objects in JavaScript have an internal property, denoted in the specification as[[Prototype]], which is simply a reference to another object. Almost all objects are given a non-nullvalue for this property, at the time of their creation.
How to get an object's prototype?
via __proto__or Object.getPrototypeOf
var a = { name: "wendi" };
a.__proto__ === Object.prototype // true
Object.getPrototypeOf(a) === Object.prototype // true
function Foo() {};
var b = new Foo();
b.__proto__ === Foo.prototype
b.__proto__.__proto__ === Object.prototype
What is the prototype ?
prototype is an object automatically created as a special property of a function, which is used to establish the delegation (inheritance) chain, aka prototype chain.
When we create a function a, prototype is automatically created as a special property on a and saves the function code on as the constructor on prototype.
function Foo() {};
Foo.prototype // Object {constructor: function}
Foo.prototype.constructor === Foo // true
I'd love to consider this property as the place to store the properties (including methods) of a function object. That's also the reason why utility functions in JS are defined like Array.prototype.forEach() , Function.prototype.bind(), Object.prototype.toString().
Why to emphasize the property of a function?
{}.prototype // undefined;
(function(){}).prototype // Object {constructor: function}
// The example above shows object does not have the prototype property.
// But we have Object.prototype, which implies an interesting fact that
typeof Object === "function"
var obj = new Object();
So, Arary, Function, Objectare all functions. I should admit that this refreshes my impression on JS. I know functions are first-class citizen in JS but it seems that it is built on functions.
What's the difference between __proto__ and prototype?
__proto__a reference works on every object to refer to its [[Prototype]]property.
prototype is an object automatically created as a special property of a function, which is used to store the properties (including methods) of a function object.
With these two, we could mentally map out the prototype chain. Like this picture illustrates:
function Foo() {}
var b = new Foo();
b.__proto__ === Foo.prototype // true
Foo.__proto__ === Function.prototype // true
Function.prototype.__proto__ === Object.prototype // true
I know, I am late but let me try to simplify it.
Let us say there is a function
function Foo(message){
this.message = message ;
};
console.log(Foo.prototype);
Foo function will have a prototype object linked. So,Whenever we create a function in JavaScript, it always has a prototype object linked to it.
Now let us go ahead and create two objects using the function Foo.
var a = new Foo("a");
var b = new Foo("b");
console.log(a.message);
console.log(b.message);
Now we have two objects, object a and object b. Both are created
using constructor Foo. Keep in mind constructor is just a word here.
Object a and b both have a copy of message property.
These two objects a and b are linked to prototype object of constructor Foo.
On objects a and b, we can access Foo prototype using __proto__ property in all browsers and in IE we can use Object.getPrototypeOf(a) or Object.getPrototypeOf(b)
Now, Foo.prototype, a.__proto__, and b.__proto__ all denotes same object.
b.__proto__ === Object.getPrototypeOf(a);
a.__proto__ === Foo.prototype;
a.constructor.prototype === a.__proto__;
all of above would return true.
As we know, in JavaScript properties can be added dynamically. We can add property to object
Foo.prototype.Greet = function(){
console.log(this.message);
}
a.Greet();//a
b.Greet();//b
a.constructor.prototype.Greet();//undefined
As you see we added Greet() method in Foo.prototype but it is accessible in a and b or any other object which is constructed using Foo.
While executing a.Greet(), JavaScript will first search Greet in object a on property list. On not finding , it will go up in __proto__ chain of a. Since a.__proto__ and Foo.prototype is same object, JavaScript will find Greet() method and execute it.
I hope, now prototype and __proto__ is simplified a bit.
Another good way to understand it:
var foo = {}
/*
foo.constructor is Object, so foo.constructor.prototype is actually
Object.prototype; Object.prototype in return is what foo.__proto__ links to.
*/
console.log(foo.constructor.prototype === foo.__proto__);
// this proves what the above comment proclaims: Both statements evaluate to true.
console.log(foo.__proto__ === Object.prototype);
console.log(foo.constructor.prototype === Object.prototype);
Only after IE11 __proto__ is supported. Before that version, such as IE9, you could use the constructor to get the __proto__.
prototype
prototype is a property of a Function. It is the blueprint for creating objects by using that (constructor) function with new keyword.
__proto__
__proto__ is used in the lookup chain to resolve methods, properties. when an object is created (using constructor function with new keyword), __proto__ is set to (Constructor) Function.prototype
function Robot(name) {
this.name = name;
}
var robot = new Robot();
// the following are true
robot.__proto__ == Robot.prototype
robot.__proto__.__proto__ == Object.prototype
Here is my (imaginary) explanation to clear the confusion:
Imagine there is an imaginary class (blueprint/coockie cutter) associated with function. That imaginary class is used to instantiate objects. prototype is the extention mechanism (extention method in C#, or Swift Extension) to add things to that imaginary class.
function Robot(name) {
this.name = name;
}
The above can be imagined as:
// imaginary class
class Robot extends Object{
static prototype = Robot.class
// Robot.prototype is the way to add things to Robot class
// since Robot extends Object, therefore Robot.prototype.__proto__ == Object.prototype
var __proto__;
var name = "";
// constructor
function Robot(name) {
this.__proto__ = prototype;
prototype = undefined;
this.name = name;
}
}
So,
var robot = new Robot();
robot.__proto__ == Robot.prototype
robot.prototype == undefined
robot.__proto__.__proto__ == Object.prototype
Now adding method to the prototype of Robot:
Robot.prototype.move(x, y) = function(x, y){ Robot.position.x = x; Robot.position.y = y};
// Robot.prototype.move(x, y) ===(imagining)===> Robot.class.move(x, y)
The above can be imagined as extension of Robot class:
// Swift way of extention
extension Robot{
function move(x, y){
Robot.position.x = x; Robot.position.y = y
}
}
Which in turn,
// imaginary class
class Robot{
static prototype = Robot.class // Robot.prototype way to extend Robot class
var __proto__;
var name = "";
// constructor
function Robot(name) {
this.__proto__ = prototype;
prototype = undefined;
this.name = name;
}
// added by prototype (as like C# extension method)
function move(x, y){
Robot.position.x = x; Robot.position.y = y
};
}
I've made for myself a small drawing that represents the following code snippet:
var Cat = function() {}
var tom = new Cat()
I have a classical OO background, so it was helpful to represent the hierarchy in this manner. To help you read this diagram, treat the rectangles in the image as JavaScript objects. And yes, functions are also objects. ;)
Objects in JavaScript have properties and __proto__ is just one of them.
The idea behind this property is to point to the ancestor object in the (inheritance) hierarchy.
The root object in JavaScript is Object.prototype and all other objects are descendants of this one. The __proto__ property of the root object is null, which represents the end of inheritance chain.
You'll notice that prototype is a property of functions. Cat is a function, but also Function and Object are (native) functions. tom is not a function, thus it does not have this property.
The idea behind this property is to point to an object which will be used in the construction, i.e. when you call the new operator on that function.
Note that prototype objects (yellow rectangles) have another property called
constructor which points back to the respective function object. For
brevity reasons this was not depicted.
Indeed, when we create the tom object with new Cat(), the created object will have the __proto__ property set to the prototype object of the constructor function.
In the end, let us play with this diagram a bit. The following statements are true:
tom.__proto__ property points to the same object as Cat.prototype.
Cat.__proto__ points to the Function.prototype object, just like Function.__proto__ and Object.__proto__ do.
Cat.prototype.__proto__ and tom.__proto__.__proto__ point to the same object and that is Object.prototype.
Cheers!
[[Prototype]] :
[[Prototype]] is an internal hidden property of objects in JS and it is a reference to another object. Every object at the time of creation receives a non-null value for [[Prototype]]. Remember [[Get]] operation is invoked when we reference a property on an object like, myObject.a. If the object itself has a property, a on it then that property will be used.
let myObject= {
a: 2
};
console.log(myObject.a); // 2
But if the object itself directly does not have the requested property then [[Get]] operation will proceed to follow the [[Prototype]] link of the object. This process will continue until either a matching property name is found or the [[Prototype]] chain ends(at the built-in Object.prototype). If no matching property is found then undefined will be returned. Object.create(specifiedObject) creates an object with the [[Prototype]] linkage to the specified object.
let anotherObject= {
a: 2
};
// create an object linked to anotherObject
let myObject= Object.create(anotherObject);
console.log(myObject.a); // 2
Both for..in loop and in operator use [[Prototype]] chain lookup process. So if we use for..in loop to iterate over the properties of an object then all the enumerable properties which can be reached via that object's [[Prototype]] chain also will be enumerated along with the enumerable properties of the object itself. And when using in operator to test for the existence of a property on an object then in operator will check all the properties via [[Prototype]] linkage of the object regardless of their enumerability.
// for..in loop uses [[Prototype]] chain lookup process
let anotherObject= {
a: 2
};
let myObject= Object.create(anotherObject);
for(let k in myObject) {
console.log("found: " + k); // found: a
}
// in operator uses [[Prototype]] chain lookup process
console.log("a" in myObject); // true
.prototype :
.prototype is a property of functions in JS and it refers to an object having constructor property which stores all the properties(and methods) of the function object.
let foo= function(){}
console.log(foo.prototype);
// returns {constructor: f} object which now contains all the default properties
foo.id= "Walter White";
foo.job= "teacher";
console.log(foo.prototype);
// returns {constructor: f} object which now contains all the default properties and 2 more properties that we added to the fn object
/*
{constructor: f}
constructor: f()
id: "Walter White"
job: "teacher"
arguments: null
caller: null
length: 0
name: "foo"
prototype: {constructor: f}
__proto__: f()
[[FunctionLocation]]: VM789:1
[[Scopes]]: Scopes[2]
__proto__: Object
*/
But normal objects in JS does not have .prototype property. We know Object.prototype is the root object of all the objects in JS. So clearly Object is a function i.e. typeof Object === "function" . That means we also can create object from the Object function like, let myObj= new Object( ). Similarly Array, Function are also functions so we can use Array.prototype, Function.prototype to store all the generic properties of arrays and functions. So we can say JS is built on functions.
{}.prototype; // SyntaxError: Unexpected token '.'
(function(){}).prototype; // {constructor: f}
Also using new operator if we create objects from a function then internal hidden [[Prototype]] property of those newly created objects will point to the object referenced by the .prototype property of the original function. In the below code, we have created an object, a from a fn, Letter and added 2 properties one to the fn object and another to the prototype object of the fn. Now if we try to access both of the properties on the newly created object, a then we only will be able to access the property added to the prototype object of the function. This is because the prototype object of the function is now on the [[Prototype]] chain of the newly created object, a.
let Letter= function(){}
let a= new Letter();
Letter.from= "Albuquerque";
Letter.prototype.to= "New Hampshire";
console.log(a.from); // undefined
console.log(a.to); // New Hampshire
.__proto__ :
.__proto__ is a property of objects in JS and it references the another object in the [[Prototype]] chain. We know [[Prototype]] is an internal hidden property of objects in JS and it references another object in the [[Prototype]] chain. We can get or set the object referred by the internal [[Prototype]] property in 2 ways
Object.getPrototypeOf(obj) / Object.setPrototypeOf(obj)
obj.__proto__
We can traverse the [[Prototype]] chain using: .__proto__.__proto__. . . Along with .constructor, .toString( ), .isPrototypeOf( ) our dunder proto property (__proto__) actually exists on the built-in Object.prototype root object, but available on any particular object. Our .__proto__ is actually a getter/setter. Implementation of .__proto__ in Object.prototype is as below :
Object.defineProperty(Object.prototype, "__proto__", {
get: function() {
return Object.getPrototypeOf(this);
},
set: function(o) {
Object.setPrototypeOf(this, o);
return o;
}
});
To retrieve the value of obj.__proto__ is like calling, obj.__proto__() which actually returns the calling of the getter fn, Object.getPrototypeOf(obj) which exists on Object.prototype object. Although .__proto__ is a settable property but we should not change [[Prototype]] of an already existing object because of performance issues.
Using new operator if we create objects from a function then internal hidden [[Prototype]] property of those newly created objects will point to the object referenced by the .prototype property of the original function. Using .__proto__ property we can access the other object referenced by internal hidden [[Prototype]] property of the object. But __proto__ is not the same as [[Prototype]] rather a getter/setter for it. Consider below code :
let Letter= function() {}
let a= new Letter();
let b= new Letter();
let z= new Letter();
// output in console
a.__proto__ === Letter.prototype; // true
b.__proto__ === Letter.prototype; // true
z.__proto__ === Letter.prototype; // true
Letter.__proto__ === Function.prototype; // true
Function.prototype.__proto__ === Object.prototype; // true
Letter.prototype.__proto__ === Object.prototype; // true
To put it simply:
> var a = 1
undefined
> a.__proto__
[Number: 0]
> Number.prototype
[Number: 0]
> Number.prototype === a.__proto__
true
This allows you to attach properties to X.prototype AFTER objects of type X has been instantiated, and they will still get access to those new properties through the __proto__ reference which the Javascript-engine uses to walk up the prototype chain.
Prototype or Object.prototype is a property of an object literal. It represents the Object prototype object which you can override to add more properties or methods further along the prototype chain.
__proto__ is an accessor property (get and set function) that exposes the internal prototype of an object thru which it is accessed.
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
http://www.w3schools.com/js/js_object_prototypes.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
Explanatory example:
function Dog(){}
Dog.prototype.bark = "woof"
let myPuppie = new Dog()
now, myPupppie has __proto__ property which points to Dog.prototype.
> myPuppie.__proto__
>> {bark: "woof", constructor: ƒ}
but myPuppie does NOT have a prototype property.
> myPuppie.prototype
>> undefined
So, __proto__ of mypuppie is the reference to the .prototype property of constructor function that was used to instantiate this object (and the current myPuppie object has "delegates to" relationship to this __proto__ object), while .prototype property of myPuppie is simply absent (since we did not set it).
Good explanation by MPJ here:
proto vs prototype - Object Creation in JavaScript
DEFINITIONS
(number inside the parenthesis () is a 'link' to the code that is written below)
prototype - an object that consists of:
=> functions (3) of this
particular ConstructorFunction.prototype(5) that are accessible by each
object (4) created or to-be-created through this constructor function (1)
=> the constructor function itself (1)
=> __proto__ of this particular object (prototype object)
__proto__ (dandor proto?) - a link BETWEEN any object (2) created through a particular constructor function (1), AND the prototype object's properties (5) of that constructor THAT allows each created object (2) to have access to the prototype's functions and methods (4) (__proto__ is by default included in every single object in JS)
CODE CLARIFICATION
1.
function Person (name, age) {
this.name = name;
this.age = age;
}
2.
var John = new Person(‘John’, 37);
// John is an object
3.
Person.prototype.getOlder = function() {
this.age++;
}
// getOlder is a key that has a value of the function
4.
John.getOlder();
5.
Person.prototype;
I'll try a 4th grade explanation:
Things are very simple. A prototype is an example of how something should be built. So:
I'm a function and I build new objects similar to my prototype
I'm an object and I was built using my __proto__ as an example
proof:
function Foo() { }
var bar = new Foo()
// `bar` is constructed from how Foo knows to construct objects
bar.__proto__ === Foo.prototype // => true
// bar is an instance - it does not know how to create objects
bar.prototype // => undefined
Every function you create has a property called prototype, and it starts off its life as an empty object. This property is of no use until you use this function as constructor function i.e. with the 'new' keyword.
This is often confused with the __proto__ property of an object. Some might get confused and except that the prototype property of an object might get them the proto of an object. But this is not case. prototype is used to get the __proto__ of an object created from a function constructor.
In the above example:
function Person(name){
this.name = name
};
var eve = new Person("Eve");
console.log(eve.__proto__ == Person.prototype) // true
// this is exactly what prototype does, made Person.prototype equal to eve.__proto__
I hope it makes sense.
What about using __proto__ for static methods?
function Foo(name){
this.name = name
Foo.__proto__.collection.push(this)
Foo.__proto__.count++
}
Foo.__proto__.count=0
Foo.__proto__.collection=[]
var bar = new Foo('bar')
var baz = new Foo('baz')
Foo.count;//2
Foo.collection // [{...}, {...}]
bar.count // undefined
(function(){
let a = function(){console.log(this.b)};
a.prototype.b = 1;
a.__proto__.b = 2;
let q = new a();
console.log(a.b);
console.log(q.b)
})()
Try this code to understand
There is only one object that is used for protypal chaining. This object obviously has a name and a value: __proto__ is its name, and prototype is its value. That's all.
to make it even easier to grasp, look at the diagram on the top of this post (Diagram by dmitry soshnikov), you'll never find __proto__ points to something else other than prototype as its value.
The gist is this: __proto__ is the name that references the prototypal object, and prototype is the actual prototypal object.
It's like saying:
let x = {name: 'john'};
x is the object name (pointer), and {name: 'john'} is the actual object (data value).
NOTE: this just a massively simplified hint on how they are related on a high level.
Update: Here is a simple concrete javascript example for better illustration:
let x = new String("testing") // Or any other javascript object you want to create
Object.getPrototypeOf(x) === x.__proto__; // true
This means that when Object.getPrototypeOf(x) gets us the actual value of x (which is its prototype), is exactly what the __proto__ of x is pointing to. Therefore __proto__ is indeed pointing to the prototype of x. Thus __proto__ references x (pointer of x), and prototype is the value of x (its prototype).
I hope it's a bit clear now.
so many good answers exist for this question, but for recap and compact form of answer that have good details I add the following:
the first thing that we must consider is when JS was invented, computers have very low memory, so if we need a process for creating new object types, we must consider memory performance.
so they located methods that object created from that specific object type need, on the separate part of memory instead of every time we create a new object, store methods besides the object.
so if we reinvent the new operator and constructor function concept with JS's new features we have these steps:
and empty object. (that will be the final result of instantiation of object type)
let empty={}
we already know that for memory performance reasons all the methods that are needed for instances of an object type are located on the constructor function's prototype property. (functions are also objects so they can have properties)
so we reference the empty object's __protp__ to the location where those methods exist.
(we consider the function that we use conceptually as the constructor, named constructor.
empty.__proto__ = constructor.prototype
we must initialize object type values.
in JS function are disconnected from objects. with dot notation or methods like bind call apply that function objects have we must tell "what is the this context of the function".
let newFunc = constructor.bind(empty)
now we have a new function that has an empty object as this context.
after execution of this function. the empty object will be filled, and the result of instantiation of type object will be this empty object if defined constructor function doesn't return(as if that will be the result of the process)
so as you see __proto__ is a property of objects that refers to other objects(in JS functions are also object) prototype object property which consisted of properties that use across instances of a specific object type.
as you can guess from the phrase, functions are objects, functions also have __proto__ property so they can refer to other object's prototype properties. this is how prototype inheritance is implemented.
my understanding is: __proto__ and prototype are all served for the prototype chain technique . the difference is functions named with underscore(like __proto__) are not aim for developers invoked explicitly at all. in other words, they are just for some mechanisms like inherit etc. they are 'back-end'. but functions named without underscore are designed for invoked explicitly, they are 'front-end'.
__proto__ is the base to construct prototype and a constructor function eg: function human(){} has prototype which is shared via __proto__ in the new instance of the constructor function. A more detailed read here
As this rightly stated
__proto__ is the actual object that is used in the lookup chain to
resolve methods, etc. prototype is the object that is used to build
__proto__ when you create an object with new:
( new Foo ).__proto__ === Foo.prototype;
( new Foo ).prototype === undefined;
We can further note that __proto__ property of an object created using function constructor points towards the memory location pointed towards by prototype property of that respective constructor.
If we change the memory location of prototype of constructor function, __proto__ of derived object will still continue to point towards the original address space. Therefore to make common property available down the inheritance chain, always append property to constructor function prototype, instead of re-initializing it (which would change its memory address).
Consider the following example:
function Human(){
this.speed = 25;
}
var himansh = new Human();
Human.prototype.showSpeed = function(){
return this.speed;
}
himansh.__proto__ === Human.prototype; //true
himansh.showSpeed(); //25
//now re-initialzing the Human.prototype aka changing its memory location
Human.prototype = {lhs: 2, rhs:3}
//himansh.__proto__ will still continue to point towards the same original memory location.
himansh.__proto__ === Human.prototype; //false
himansh.showSpeed(); //25

Prototype keyword in Javascript

What is prototype property, and why is it necessary? So far, I have learnt that this provides public access to more intrinsic, and private prototype of the object; is that correct?
Also, what's the difference between following statements?
MyConstructor.age = 30;
MyConstructor.prototype.age = 30;
In short, I need a better understanding of keyword prototype.
Thanks
"Prototype" is something that plays a role in objects.
In Javascript, everything is an object. Every object has a kind, and thus inherits the prototype of that kind.
For example, take a simple array: var a = []. You can make operations with it, like a.push(10). Where does this push method come from? From the prototype of Array object, which a is.
You can add your own methods to Array objects just by defining them in the prototype object. For example:
Array.prototype.sortNum = function() {this.sort(function(a, b) {return a - b});};
This way you can do something like a.sortNum() with all arrays, even the ones created before you defined the sortNum method.
(Note: for compatibility reasons, it's usually not recommended to extend the prototype of native objects like Arrays. But this particular example is usually a welcome addition, as well as normalizing methods like map and forEach for older browsers.)
(Just never ever extend Object.prototype! Unless you don't care to mess up for...in statements, the in operator and these sort of cases.)
If you want to define your own classes, like the name MyConstructor suggests, you'll have to define its prototype to define the methods for all the instances of that class:
function MyConstructor(name) {this.name = name};
MyConstructor.prototype = {
print: function() {return this.name;}
};
var mc = new MyConstructor("foo");
alert(mc.print()); // alerts "foo"
You can define more than just functions in prototypes, too:
MyConstructor.prototype.age = 30;
alert(mc.age); // alerts 30
Watch out when you do this to define "default" object values, because changing it may cause a change in all instances of that class.
But this comes handy with Object.defineProperty:
Object.defineProperty(MyConstructor.prototype, "wholeString", {
get: function() {return this.name + "=" + this.age;},
set: function(v) {this.name = v.substring(3);}
});
alert(mc.wholeString); // alerts "foo = 30"
(Unfortunately, IE<9 allows this only for DOM objects...)
When you define MyConstructor.age = 30 instead, what you're actually doing is defining a member of the function MyConstructor, so mc.age would be undefined. Every instance of MyConstructor inherits the methods and members defined in MyConstructor.prototype, not the ones of the function MyConstructor.
There's much more to say, actually. Objects can be of a subclass of another class, thus inheriting the prototype of the superclass, too. For example, document.body is an instance of HTMLBodyElement, which is a subclass of HTMLElement, which is a subclass of Element and so on, until you get Object as the upmost superclass. So, document.body inherits all the methods defined in the prototype of HTMLBodyElement, HTMLElement, Element and Object. This is called the prototype chain.
Doing the same with custom objects is a bit tricky:
function Class() {};
Class.prototype.foo = function() {alert("foo");};
function Subclass() {};
Subclass.prototype = new Class();
Subclass.prototype.bar = function() {alert("bar");};
var a = new Class(), b = new Subclass();
a.foo(); // alerts"foo"
a.bar(); // throws an error
b.foo(); // alerts "foo"
b.bar(); // alerts "bar"
a instanceof Class; // true
a instanceof Subclass; // false
b instanceof Class; // true
b instanceof Subclass; // true
In JavaScript, function objects have a built-in .prototype property. The value of this property is an object. If the function is used as a constructor, the resulting instances inherit from that "prototype" object.
Example:
var Dog = function () {}; // the constructor function
Dog.prototype.bark = function () {}; // adding a method to Dog.prototype
var dog1 = new Dog; // creating a new instance
dog1.bark(); // the instance inherits the "bark" method from Dog.prototype
Note that the .prototype property (of function objects) is not the same as the [[Prototype]] internal property. All objects contain the latter. It's an internal reference to an object's prototype. (In the above example, the dog1 object's [[Prototype]] refers to Dog.prototype.) On the other hand, only function objects have a built-in .prototype property (which makes sense since only function objects can be used as constructors).
var foo = function () {};
foo.bar = 5;
foo.prototype.foobar = 10;
var x = new foo();
x.bar; // undefined
x.foobar; // 10
Edit: Also, you can then do
foo.prototype.foobar = 20;
x.foobar; // 20

Is there a good use case for the constructor property in Javascript?

First off, this question is not "what does the constructor property do?" - There's plenty of good documentation on exactly what it is and how it works: It's a reference to the function that created the object (which may be inherited from its prototype).
I'm more interested in knowing common use-cases for this property. It seems all good in theory, but when would you actually need a reference to the function that constructed your object? A few ideas would be:
Perhaps I want to clone it. I could call the constructor again and
get another instance of my object. This of course wouldn't work well
since you'd potentially be creating an instance of your object's
prototype, not the object itself; plus a much preferred method would
be to create a new object and set that object's prototype instead.
Perhaps you can use it to figure out what the "type" of the object
is. This seems rather odd, since you can use instanceof or
Object.prototype.toString() instead.
Can you change or re-assign the constructor? Would there ever be a good reason to
do this?
Hopefully some people can chime in with some good Javascript paterns that make use of the constructor reference, or provide an official explanation for why the property exists.
One case where the constructor property is handy (or would be if it was reliable) is where a function needs to know the type of argument it has been passed, e.g.
function foo(arg) {
if ( /* if arg is an array */ ) {
// deal with array
} else if ( /* if arg is an object */ ) {
// deal with object
}
}
If the above function is passed an array or object, then typeof will return object in both cases. The constructor property can be used:
if ( arg.constructor == Array )
But that fails if the array is created in a different frame to where the test is taking place (i.e. it's Array constructor is a different object to the Array function in the scope of the test).
So if you rule out frames (or other cases where scope is an issue), then the constructor property is fine to use for this.
But that does not fix the general issue of the constructor property being writable (and therefore can be set to anything) and cases where the prototype chain is more than trivial.
One of the good use cases is implementation of "inheritance" and "classes in javascript. Let's consider the following example:
// define the Person Class
function Person() {}
Person.prototype.walk = function(){
alert ('I am walking!');
};
Person.prototype.sayHello = function(){
alert ('hello');
};
// define the Student class
function Student() {
// Call the parent constructor
Person.call(this);
}
// inherit Person
Student.prototype = new Person();
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
// replace the sayHello method
Student.prototype.sayHello = function(){
alert('hi, I am a student');
}
// add sayGoodBye method
Student.prototype.sayGoodBye = function(){
alert('goodBye');
}
var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();
// check inheritance
alert(student1 instanceof Person); // true
alert(student1 instanceof Student); // true
As you can see we've inherited Person, by reassigning Student.prototype to new Person();, but then we need to reassign constructor back to Student as we want to create instance of Student class, but not a Person.
UPDATE
Btw, more real-world example of inheritance in javascript is to use intermediate function, so Person object will not be created during definition stage:
// inherit Person
function F() {}
F.prototype = Person.prototype;
Student.prototype = new F();
I've used it before for type checking. It's not much more useful than instanceof, but it's a little more explicit.
function isArray(o) {
return o.constructor == Array;
}

Categories

Resources