Why is the function declared in the prototype not declared?

var p = function () { this.show = function () { alert('hello world!!!'); } } p.prototype.show = function() { alert('haha'); } var o = new p(); o.show(); 

It alerts "hello world!!!" why?

Can I modify the prototype of the method, if so, how?

+8
javascript inheritance prototype
source share
3 answers

This is because the specific function that you define in the constructor overrides the one that is inherited through the prototype.

From EcmaScript Specification :

Each object created by the constructor has an implicit reference (the so-called prototype of objects) to the value of its constructors "prototype" property. In addition, the prototype may have a non-zero implicit reference to its prototype, etc .; this is called a prototype circuit. When a reference is made to a property of an object, this reference refers to the property of this name in the first object in the prototype chain that contains the property of this name. In other words, first the object mentioned directly is considered for such property; if this object contains a named property, that is, the property to which the link refers; if this object does not contain a named property, the prototype for this object is checked as follows; etc.

In short: when you search for a function (or any property by its name), you start with an object, and then go into the prototype chain.

+7
source share

You will override the prototype.show method in p .

+3
source share

In Javascript, when a property is enabled, the engine first looks at the properties of the object. In your example, the object will be represented by this . If he finds a property, in this case show (remember that functions can be properties), he uses this property. If the property is not found, iterates through the prototype chain in an attempt to resolve the property.

+1
source share

All Articles