[TOC]
## 7.1 this
* javascript的頂級作用域是window,全局變量是widow的屬性,函數是window的方法;
` this的指向:`
* 1.在事件中,this指向正在執行事情的當前對象
* 2.在方法中,誰調用方法,this指向誰
~~~
var a = 10;
// window.a=10;
function b(){
console.log(this.a); //10
}
// window.b();
b();
console.log(window.a); //10
~~~
## 7.2 this 指向
> .函數作為普通函數調用,this指向window
~~~
<!--
自定義屬性data-name=value
-->
<input type="button" value="hello" id="test">
<script>
var value = "change"
var test = document.getElementById("test");
test.onclick = function(){
// setTimeout(function(){
// console.log(this.value); //hello
// },300)
go(); //this還是指向window-->函數正常調用,this指向window
}
function go(){
console.log(this.value);
}
</script>
~~~
### 7.2.1 bind 改變函數內部this關鍵字的指向
> bind后函數不會執行,而只是返回一個改變了上下文的函數副本,而call和apply是直接執行函數
~~~
<!--
自定義屬性data-name=value
-->
<input type="button" value="hello" id="test">
<script>
var value = "change"
var test = document.getElementById("test");
test.onclick = function(){
setTimeout(function(){
console.log(this.value); //hello
}.bind(this),300)
}
</script>
* * * * *
<script>
// bind-->改變函數內部this關鍵字的指向
var name = "zhang";
var obj = {
name:"cheng"
};
var func = function(){
console.log(this.name);
}.bind(obj);
func();
</script>
~~~
### 7.2.2 call/apply
> call --> 改變函數內部this ,關鍵字的指向 call(thisObj,params)
apply -->改變函數內部this關鍵字的指向 apply(thisObj,[params]) //傳值傳數組z
```
var cheng = {
name:"cheng"
}
var jiang = {
name:"jiang",
sayName(a,b){
console.log(this.name)
console.log(a+b);
}
}
jiang.sayName.call(cheng,1,2); // cheng 3
jiang.sayName.apply(cheng,[1,3]); //cheng 4
```
### 7.2.3 this 中使用箭頭函數
* 箭頭函數可以改變函數的this指向
~~~
<!--
自定義屬性data-name=value
-->
<input type="button" value="hello" id="test">
<script>
var value = "change"
var test = document.getElementById("test");
test.onclick = function(){
setTimeout(()=>{
console.log(this.value);
},300)
}
</script>
~~~
## self.value
~~~
<!--
自定義屬性data-name=value
-->
<input type="button" value="hello" id="test">
<script>
var value = "change"
var test = document.getElementById("test");
test.onclick = function(){
var self = this
setTimeout(function(){
console.log(self.value); //hello
},300)
}
</script>
~~~
- 效果實例
- 1.點擊增加高度
- 2.tab頁面切換
- 3. 列表切換
- 4. 隔行變色
- 5. swiper 輪播
- 6.vue
- 7.定時器
- 8. 向表格中添加數據
- 9 瀑布流
- 1.JavaScript基礎
- 1. 變量
- 2. 調試
- 3.數據類型
- 4.轉換
- 5.控制語句
- 6.運算
- 7. this
- 8 JSON對象和javascript對象的相互轉換
- 2.JavaScript的控制語句
- 1. 基本控制語句
- 2.節點
- 2.1DOM補充
- 3. 函數
- js的模塊化如何解決
- 不知道有什么用的
- 4.數組
- 5. String
- 補充
- 6.Ajax
- 1. 原生Ajax
- 2. HTTP/get/post
- 3.jQuery-Ajax
- 4.跨域
- 5.axios
- 6.封裝
- Ajax效果
- ajax補充
- 7. 正則
- 1.創建正則表達式
- 2. 正則的api
- 3.正則語法
- 4.例子
- 量詞
- 8.面向對象
- 1.原型
- ES6
- 模塊化
- 1.回調地獄
- 什么是回調地獄
- 簡單封裝
- promise解決回調地獄
- generator解決回調地獄
- async解決回調地獄
- 2.封裝
- Ajax,promise
- JavaScript難點
- 1. 閉包/作用域
- 2.原型鏈
- 3. 兼容性
- 適配
- JavaScript小效果
- 字符串截取