var obj = {
name: 'qiutc'
};
function foo() {
console.log(this);
}
foo.call(obj);
// Object {name: "qiutc"}
可以看到,在執行 foo.call(obj) 的時候,函數內的 this 指向了 obj 這個對象,成功;
為對象中的方法指定一個 this
var obj = {
name: 'qiutc',
foo: function () {
console.log(this);
}
}
var obj2 = {
name: 'tcqiu222222'
};
obj.foo.call(obj2);
// Object {name: "tcqiu222222"}
可以看到,執行函數的時候這裡的 this 指向了 obj2,成功;
為構造函數指定 this
function Person(name) {
this.name = name;
console.log(this);
}
var obj = {
name: 'qiutc2222222'
};
var p = new Person.call(obj, 'qiutc');
// Uncaught TypeError: Person.call is not a constructor(…)
這裡報了個錯,原因是我們去 new 了 Person.call 函數,而非 Person ,這裡的函數不是一個構造函數;
換成 bind 試試:
function Person(name) {
this.name = name;
console.log(this);
}
var obj = {
name: 'qiutc2222222'
};
var Person2 = Person.bind(obj);
var p = new Person2('qiutc');
// Person {name: "qiutc"}
console.log(obj);
// Object {name: "qiutc2222222"}
打印出來的是 Person 實例化出來的對象,而和 obj 沒有關係,而 obj 也沒有發生變化,說明,我們給 Person 指定 this 上下文並沒有生效;
因此可以得出: 使用 bind 給一個構造函數指定 this,在 new 這個構造函數的時候,bind 函數所指定的 this 並不會生效;
當然 bind 不僅可以指定 this ,還能傳入參數,我們來試試這個操作:
function Person(name) {
this.name = name;
console.log(this);
}
var obj = {
name: 'qiutc2222222'
};
var Person2 = Person.bind(obj, 'qiutc111111');
var p = new Person2('qiutc');
// Person {name: "qiutc111111"}
可以看到,雖然指定 this 不起作用,但是傳入參數還是起作用了;
為箭頭函數指定 this
我們來定義一個全局下的箭頭函數,因此這個箭頭函數中的 this 必然會指向全局對象,如果用 call 方法改變 this 呢:
var getAge = function(){
'use strict'
console.log(this.age);
};
getAge(null);//報錯 age未定義
再來理解this的使用
this的常用場景:
this位於一個對象的方法內,此時this指向該對象
var name = 'window';
var Student = {
name : 'kobe',
getName: function () {
console.log(this == Student); //true
console.log(this.name); //kobe
}
}
Student.getName();
var name = 'window';
var Student = {
name : 'kobe',
getName: function () {
var name=100;
console.log(this == Student); //true
console.log(this.name); //kobe
}
}
Student.getName(); //getName取得是Student 的name
this位於一個普通的函數內,表示this指向全局對象,(瀏覽器是window)
var name = 'window';
var getName = function () {
var name = 'kobe'; //迷惑性而已
return this.name;
}
console.log( getName() ); //window
this使用在構造函數(構造器)裡面,表示this指向的是那個返回的對象.
var name = 'window';
//構造器
var Student = function () {
this.name = 'student';
}
var s1 = new Student();
console.log(s1.name); //student
var name = 'window';
//構造器
var Student = function () {
this.name = 'student';
return {
name: 'boyStudent'
}
}
var s1 = new Student();
console.log(s1.name); //boyStudent
this指向失效問題
var name = 'window';
var Student = {
name : 'kobe',
getName: function () {
console.log(this.name);
}
}
Student.getName(); // kobe
var s1 = Student.getName;
s1(); //window