Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where the `prototype` property is defined

Well, all the time i supposed that prototype property exists at all objects. But after one of job interview i came home and open chrome console

window.prototype
**undefined**

WTF?

Object.prototype
**Object {}**

OK

var a = {};
a.prototype
**undefined**

var a = function(){}
a.prototype
**Object {}**

I've read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype several times but still not clear. Can anybody explain?

Thanx

P.S. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype, although they may be overridden (except an Object with a null prototype, i.e. Object.create(null)

window is Object, so it must have prototype property

like image 642
Vasiliy Vanchuk Avatar asked Jun 13 '14 14:06

Vasiliy Vanchuk


People also ask

What is a prototype property?

Whenever we create a JavaScript function, JavaScript adds a prototype property to that function. A prototype is an object, where it can add new variables and methods to the existing object. i.e., Prototype is a base class for all the objects, and it helps us to achieve the inheritance.

What is prototype property explain with an example?

The prototype property is an object which contains a constructor property and its value is Point2D function: Point2D.prototype.constructor = Point2D . And when you call Point2D with new keyword, newly created objects will inherit all properties from Point2D.prototype .

Do all functions have a prototype property?

Note: Not all Function objects have the prototype property — see description.

How do you get the prototype of an object?

The Object. getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.


1 Answers

The object an instance inherits from, its prototype, is stored in an internal property, [[Prototype]]. Its value can be retrieved with Object.getPrototypeOf() (in ES5-compatible engines).

console.log(Object.getPrototypeOf(window));
// Window { ... }

var a = {};
console.log(Object.getPrototypeOf(a));
// Object { ... }

Only functions explicitly have a prototype property:

console.log(typeof Object);
// 'function'

And, the value of the prototype is just used to set the value of the instance's [[Prototype]] when a new instance is created.

function Foo() {}
var bar = new Foo();

console.log(Foo.prototype === Object.getPrototypeOf(bar)); // true
like image 70
Jonathan Lonowski Avatar answered Oct 10 '22 08:10

Jonathan Lonowski