彻底理解javascript中的this指针
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了彻底理解javascript中的this指针,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2980字,纯文字阅读大概需要5分钟。
内容图文
![彻底理解javascript中的this指针](/upload/InfoBanner/zyjiaocheng/813/c654e9bc3eed4264bd50a0e03479972a.jpg)
this关键字对于javascript初学者,即便是老手可能都是一个比较容易搞晕的东西。本文试图理顺这个问题。
实际上js中的this和我们自然语言中的代词有类似性。比如英语中我们写"John is running fast because he is trying to catch the train"
注意上面的代词"he",我们当然可以这样写:"John is running fast because John is trying to catch the train" ,这种情况下我们没有使用this去重用代替John。
在js中this关键字就是一个引用的shortcut,他指代一个object,是执行的代码body的context环境。看下面的代码:
var person = { firstName: "Penelope", lastName: "Barrymore", fullName: function () { ?// Notice we use "this" just as we used "he" in the example sentence earlier?: console.log(this.firstName + " " + this.lastName); ?// We could have also written this:? console.log(person.firstName + " " + person.lastName); } }
如果我们使用person.firstName,person.lastName的话,我们的代码可能会产生歧义。比如,如果有一个全局变量,名字就是person,那么person.firstName可能试图从全局的person变量来访问其属性,这可能导致错误,并且难以调试。因此,我们使用this关键字,不仅为了代码更美(作为以个referent),而且为了更加精确而不会产生歧义。类似于刚刚举例的自然语言中,因为代词"he"使得句意更清晰,因为更加清晰地表明我们正在引用一个特定的John这个人。
正如代词"he"用于引用存于context中无歧义的名词一样,this关键字用于引用一个对象,而这个对象就是function(在该函数中,使用了this指针)所绑定的对象.(the this keyword is similarly used to refer to an object that the function(where this is used) is bound to.) t
this基础
首先,需要知道的是js中的所有函数都有peroperties,就像objects都有properties一样。当一个函数执行时,"it gets the this property ---- a variable with the value of the object that invokes the function where this is used"
this总是指向或者说引用(并包含了对应的value)一个对象,并且this往往在一个function或者说method中来使用。注意:虽然在global scope中我们可以不在function body中使用this,而是直接在global scope中使用this(实际上指向了window),但是如果我们在strict mode的话,在global function中,或者说没有绑定任何object的匿名函数中,如果使用this, 那么这个this将是undefined值.
假设this在一个function A中被使用,那么this就将引用着调用 function A的那个对象。我们需要这个this来访问调用function A对象的method和property.特别地,有些情况下我们不知道调用者对象的名称,甚至有时候调用者对象根本没有名字,这时就必须用this关键字了!
var person = { firstName :"Penelope", lastName :"Barrymore", // Since the "this" keyword is used inside the showFullName method below, and the showFullName method is defined on the person object, // "this" will have the value of the person object because the person object will invoke showFullName () showFullName:function () { console.log (this.firstName + " " + this.lastName); } } person.showFullName (); // Penelope Barrymore
再看一个jquery事件处理函数中使用this关键字的常见例子:
// A very common piece of jQuery code $ ("button").click (function (event) { // $(this) will have the value of the button ($("button")) object // because the button object invokes the click () method console.log ($ (this).prop ("name")); });
内容总结
以上是互联网集市为您收集整理的彻底理解javascript中的this指针全部内容,希望文章能够帮你解决彻底理解javascript中的this指针所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。