Maison > interface Web > js tutoriel > le corps du texte

说一说javascript的“this”

伊谢尔伦
Libérer: 2016-12-05 10:01:53
original
885 Les gens l'ont consulté

JS中不容易懂的概念除了闭包之外,还有一个应该是首当其冲:this ,这个东西经常让人搞混,那么今天我们就来好好看看它的庐山真面目。

定义一个对象:

var Charles = {
    living: true,
    age:23,
    gender:male,
    getGender:function(){ return Charles.gender;
    }
}; console.log(Charles.getGender()); //输出:male
Copier après la connexion

下面的代码有一样的效果:

var Charles = {
    living: true,
    age:23,
    gender:male,
    getGender:function(){ return this.gender; //注意“this” }
}; console.log(Charles.getGender()); //输出:male
Copier après la connexion

那么,this究竟在代码里指代的是什么?我们该怎么分析,因为在具体的环境里有时很难分清this指代的真面目。那么,现在,需要记住一句话:
当this值的宿主函数被封装在另一个函数里面,或者在另一个函数的上下文中被调用时,this值永远是对全局(head/window)对象的引用。
也就是说,this值在嵌套函数里面,对于ES5永远指向window。

var myObject = {
    myProperty: 'I can see the light',
    myMethod: function(){ var that = this; console.log(this); 
    //输出:'Object(这里是myObject)' var helperFunction = function(){ console.log(that.myProperty); 
    // 输出'I can see the light' console.log(this); //如果不使用`that`,则输出'window',因为是在嵌套函数里面 }(); //立即执行 }
}
myObject.myMethod(); //调用 myMethod
Copier après la connexion

结合上面的那句话,对于ES5来说,this也就是这个情况:

var myObject = {
    func1: function(){ console.log(this); //输出 'Object'(第一层函数) var func2= function(){ console.log(this); 
    //从此处开始,this都是window(第二层函数) var func3= function(){ console.log(this); //当然是window }();
        }();
    }
}
myObject.func1();
Copier après la connexion

2329.jpg

如图

到这里,应该明白了this在JS中的位置,相信以后不会再分不清楚了。


Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!