Scope
Ability to invoke a function to access a variable
//Global VariablesvarGlobalVariable = ' This is global variable '//Global Functionsfunctionglobalfunction () {//Local Variables varLocalvariable = ' This is local variable 'Console.log (' Visit gloabl/local variable ') Console.log (globalvariable) console.log (localvariable) globalvariable= ' This was change variable 'Console.log (globalvariable)//Local Functions functionloaclfunction () {//Local Variables varInnerlocalvariable = ' This is inner local variable 'Console.log (' Visit gloabl/local/innerlocal variable ') Console.log (globalvariable) console.log (localvariable) Console.log (innerlocalvariable)} //Accessible local functions within a scopeloaclfunction ()}//local variables and functions cannot be accessed globallyGlobalfunction ()
Context
Related to the This keyword, is a reference to an object that invokes the current executable code
This points to the function owner and can only be used in functions
This points to the constructor function
var pet = { words:' ... ' , speak:function() { Console.log (this. Words) Console.log ( This = =pet) }}pet.speak ()
This points to the global object
function Pet (words) { this. Words = words console.log (this. words) Console.log (this = = Global)}//This points to the global globally object Pet (' ... ')
This points to the instance object
function Pet (words) { this]words = words thisfunction() { Console.log (this. words) Console.log (this) }} varNew Pet (' Miao ') cat.speak ();
Using call and apply to change the context reference object this points to the object referencing the method
var pet = { words:' ... ' , speak:function(say) { this. Words) }}pet.speak (' haha ‘)
Using call-apply
var pet = { words:' ... ' , speak:function(say,free) { this. Words }}var dog={ words:' Wawa '}pet.speak.call (dog,' haha ', ' lala ') pet.speak.apply (dog, [' haha ', ' lala '])
Use call and apply for inheritance convenience
function Pet (words) { this]words = words thisfunction() { Console.log (this. words) }}//Dog Inherits Pet, owning the Speak method of Pet function Dog (words) { Pet.call (this, words)}varNew Dog (' Wawa ') dog.speak ()
06 MU class Network "Attack on node. JS Foundation (i)" Scope and context