this
var a = {
name:'A',
fn:function(){
console.log(this.name);
}
}
a.fn()
a.fn.call({name:'B'})
var fn1 = a.fn;
fn1()
- 作为构造函数执行
- 作为对象属性执行
- 作为普通函数执行
- call apply bind
function Foo(name){
this.name = name;
}
var f = new Foo('zhangsan');
var obj = {
name:'A',
printName:function(){
console.log(this.name);
}
}
obj.printName()
function fn(){
console.log(this);
}
fn()
function fn1(name) {
alert(name);
console.log(this);
}
fn1.call({x:100},'zhangsan',20);
var fn2 = function fn2(name) {
alert(name);
console.log(this);
}.bind({y:200});
fn2('zhangsan',20);
this几种不停的使用场景
- 作为构造函数执行
- 作为对象属性执行
- 作为普通函数执行
- call apply bind
function Foo(name){
this.name = name;
}
var f = new Foo('zhangsan');
var obj = {
name:'A',
printName:function(){
console.log(this.name);
}
}
obj.printName()
function fn(){
console.log(this);
}
fn()
// call apply bind
function fn1(name) {
alert(name);
console.log(this);
}
fn1.call({x:100},'zhangsan',20);
// bind
var fn2 = function fn2(name) {
alert(name);
console.log(this);
}.bind({y:200});
fn2('zhangsan',20);