var obj = { name: 'qiutc', foo: function () { console.log(this); } } var obj2 = { name: 'tcqiu222222' }; obj.foo.call(obj2); // Object {name: "tcqiu222222"}
能夠看到,執行函數的時候這裏的 `this` 指向了 `obj2`,成功;
3. 爲構造函數指定 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(…)
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"}
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"}