The code information comes from http://ejohn.org/apps/learn/.
Add a method to a prototype of a function
function Ninja () {} function () { returntrue;}; var New "Method exists and is callable.");
It can be accessed by instantiating an object, because the object that the constructor instantiates has the __proto__ property value is the constructor's prototype, and if the instantiated object itself does not have this method, it automatically accesses the __proto__, so it can invoke the method in the prototype.
Call Order
function Ninja () { this . Swingsword = function () { Span style= "color: #0000ff;" >return true ; }; // should return false, but would be overridden Ninja.prototype.swingSword = function () { return false ; }; var ninja = new Ninja (); Console.log (Ninja.swingsword (), "invokes an instantiated object method, not a prototype");
This example provides a good indication of the order of calls: first accessing the instantiated object itself, if not accessing its function prototype.
The transformation of the prototype affects all the instantiated objects that inherit it
function Ninja () { thistrue;} var New varnew Ninja (); function () { returnthis. swung;}; " Even after the definition, the method still exists"the same situation");
As previously stated, instantiating a property that the object itself does not have, it goes to the prototype of the function to look for. If the prototype is modified, it will look for different results.
Problem: Building a method that can be chained to a call
function Ninja () { thistrue;} var New varnew Ninja (); // add a method to the prototype, return the caller, and modify the value of the swung Console.log (ninjaa.swing (). swung); Console.log (Ninjab.swing (). swung);
By returning this implementation
function Ninja () { thistrue;} var New Ninja.prototype.swingfunction() { thisfalse ; return This
This points to the object that called it, returns this in the method, and is still the object that called it when the function finishes executing.
JavaScript advanced Knowledge Point--function prototype