In learning JavaScript, functions are very important, and now I'm going to talk about the understanding of functions and some techniques in work and usage.
Technique One,
"Scope-Safe constructors"
The constructor is actually a function called with the new operation
function Person (name,age,job) { this. name=name; this. age= age; this. job=job;} var person=New person (' match ', software, ' Engineer '); Console.log (person.name); // Match
If there is no new action, the three attributes that were originally intended for the person object are added to the Window object
function Person (name,age,job) { this. name=name; this. age= age; this. job=job;} var person=person (' Match ', software, ' Engineer '); Console.log (person); // undefinedconsole.log (window.name); // Match
As shown in the code above, the direct person is a undefined, but the attributes in person are added to the Window object
Window's Name property is used to identify the link target and frame, where accidental overwriting of the property may result in other errors on the page, the problem is to create a scope-safe constructor
functionPerson (name,age,job) {if( This instanceofPerson ) { This. name=name; This. age=Age ; This. job=job; }Else{ return NewPerson (Name,age,job); }}varPerson=person (' Match ', software, ' Engineer '); Console.log (Window.name); // ""Console.log (Person.name);//' Match 'varperson=NewPerson (' match ', ' software Engineer '); Console.log (Window.name); // ""Console.log (Person.name);//' Match '
However, the inheritance of the constructor stealing pattern is a side effect because, in the following code, the This object is not an Polygon object instance, so the constructor polygon () is created to return a new instance
functionPolygon (sides) {if( This instanceofPolygon) { This. sides=sides; This. getarea=function(){ return0; } }Else{ return NewPolygon (sides); }}functionRectangle (wifth,height) {Polygon.call ( This, 2); This. width= This. Width; This. height=height; This. getarea=function(){ return This. Width * This. Height; };}varrect=NewRectangle (5,10); Console.log (rect.sides); //undefined
If you want to use a scope-safe constructor stealing mode, you need to combine the prototype chain inheritance, overriding the Rectangle prototype property, and making its instance an instance of polygon
functionPolygon (sides) {if( This instanceofPolygon) { This. sides=sides; This. getarea=function(){ return0; } }Else{ return NewPolygon (sides); }}functionRectangle (wifth,height) {Polygon.call ( This, 2); This. width= This. Width; This. height=height; This. getarea=function(){ return This. Width * This. Height; };} Rectangle.prototype=NewPolygon ();varrect=NewRectangle (5,10); Console.log (rect.sides); //2
These are some of the understanding of scope security! The next few articles will explain the lazy loading function
Three tips in JavaScript functions "one"