javascript
JavaScript中this指向问题
函數中的this指向:
????DOM(文檔對象模型的頂級對象是:document)
????BOM(瀏覽器對象模型的頂級對象是:window)
apply()和call()改變this的指向:
/*
* apply()的使用語法
*?? 函數名字.apply(對象, [參數1, 參數2, 參數3......])
*?? 方法名字.apply(對象, [參數1, 參數2, 參數3......])
* call()的使用語法
*?? 函數名字.call(對象, 參數1, 參數1, 參數1)
*?? 方法名字.call(對象, 參數1, 參數1, 參數1)
*
* 作用:改變this的指向
* 不同的地方:參數傳遞的方式是不一樣的
*
* 只要是想使用別的對象的方法,并且希望這個方法是當前對象的,那么就可以使用 apply() 或者是 call() 來改變 this 的指向。
* */
// 演示代碼1
function Person(name, age){
??? this.age;
??? this.fun1 = function (a, b) {
??????? console.log("這是人的方法:a+b="+? (a+b) + "; " + this.score);
??? }
}
function Student(score) {
??? this.score = score;
}
var per = new Person("張三", 25);
var stu = new Student(100);
// 未改變 this 指向前
per.fun1.apply(null, [10,20]);?? // 這是人的方法:a+b=30; undefined
per.fun1.call(null, 10, 20);??? // 這是人的方法:a+b=30;undefined
// 改變 this 指向
per.fun1.apply(stu, [10, 20]); // 這是人的方法:a+b=30; 100
per.fun1.call(stu, 10, 20);??? // 這是人的方法:a+b=30; 100
/*
* 從上可以看出,score 是 Student 的屬性,fun1 是 Person 的方法,通過傳入對象
* stu,修改了 fun1 中 this 的指向為 stu,從而獲得了 stu 屬性值 score。
* */
// apply()和call()方法來自哪里?
console.log(per.fun1.__proto__ == Function.prototype); // 表明所有函數對象都是Function的實例對象
console.log(Function.prototype); // { [nativecode] }
// apply() 和 call() 方法實際上并不在函數這個實例對象中,而是在Function的prototype中
bind()復制函數
f/*bind是用來復制一份 * 使用的語法: *?? 函數名字.bind(對象, 參數1, 參數2, 參數3); ----->返回值是復制之后的這個函數 *?? 方法名字.bind(對象, 參數1, 參數2, 參數3); ----->返回值是復制之后的這個函數 * */ function Person(name, age){this.name = name;this.age = age;Person.prototype.play = function () {console.log(this.name + "在玩");} } function Student(name, age, score){this.name = name;this.age = age;this.score =score; } var per = new Person("小明", 15); var stu = new Student("小張", 16, 200); // 復制 per 的 play() 方法給ff,并修改 this 指向(由 per 指向 stu) var ff = per.play.bind(stu); ff(); // 小張在玩與50位技術專家面對面20年技術見證,附贈技術全景圖
總結
以上是生活随笔為你收集整理的JavaScript中this指向问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 正则表达式(基础、常用)----Java
- 下一篇: JavaScript中的作用域、作用域链