javascript
JS中this关键字
this是javascript的一個關鍵字,隨著函數使用場合不同,this的值會發生變化。但是總有一個原則,那就是this指的是調用函數的那個對象。
1.全局代碼中的this
alert(this);//window
this指向全局對象。
2.作為單純的函數調用
function fooCoder(x) {
? ? this.x = x;
}
fooCoder(2);
alert(x);// 全局變量x值為2
this指向全局對象,即window。在嚴格模式中,則是undefined。
3.作為對象的方法調用
var name = "clever coder";
var person = {
? ? name : "foocoder",
? ? hello : function(sth){
? ? ? ? console.log(this.name + " says " + sth);
? ? }
}
person.hello("hello world");//foocoder says hello world
this指向person對象,即當前對象。
4.作為構造函數
new FooCoder();
this指向新創建的對象。
5.內部函數
var name = "clever coder";
var person = {
? ? name : "foocoder",
? ? hello : function(sth){
? ??? ??var sayhello = function(sth) {
? ? ? ? ? ? console.log(this.name + " says " + sth);
? ? ? ? };
? ? ? ? sayhello(sth);
? ? }
}
person.hello("hello world");//clever coder says hello world
在內部函數中,this沒有按預想的綁定到外層函數對象上,而是綁定到了全局對象。
6.使用call和apply設置this
person.hello.call(person, "world");//apply和call類似,只是后面的參數是通過一個數組傳入,而不是分開傳入
兩者都是將某個函數綁定到某個具體對象上使用,自然此時的this會被顯式的設置為第一個參數。
posted on 2016-07-21 12:12 曉霜 閱讀(...) 評論(...) 編輯 收藏轉載于:https://www.cnblogs.com/zhweb/p/5691292.html
總結
以上是生活随笔為你收集整理的JS中this关键字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css选择器、权重
- 下一篇: JavaScript window.ge