js中的上下文常常代表this變量的值,以及this變量的指向,當一個函數當作一個方法被調用時,this指向的是調用這個方法的對象
通過以下幾種實例來了解一下
第一種情況,作為對象的方法
var pet={ Words:"...", speak:function(){ console.log(this.words); console.log(this==pet); }}pet.speak();控制臺輸出:
...true說明this指向的就是對象pet
第二種情況,直接調用函數
function pet(words){ this.words=words; console.log(this.words); console.log(this==globle);}pet('...');控制臺輸出:
...true說明調用pet方法的并不是pet本身,而是node.js中的頂層對象globle
第三種情況,構造函數
function Pet(words){ this.words=words; this.speak=function(){ console.log(this.words); console.log(this); }}var cat = new Pet('Miao')cat.speak()控制臺輸出:
MiaoPet { words: 'Miao', speak: [Function] }新聞熱點
疑難解答