var obj = {
name: "yan",
say: function() {
console.log(this);
}
};
var obj1 = {
say: obj,
say1: obj.say
};
obj1.say.say(); //this obj
obj1.say1(); //this obj1
var a = 1;
console.log(this.a); //window
var obj = {
a: 2,
fire: function() {
var a = 3;
console.log(this.a); //2 obj.a-->2
function innerFire() {
var a = 4;
console.log(this, this.a); //window,window.a-->1
}
// 因为声明调用对象,所以指向window
// 没有任何对象调用它,this 指向window
innerFire(); //1
console.log(this.a); //2 obj.a-->2
}
};
obj.fire();
var name = "yq";
var obj = {
name: "yan",
person: {
name: "zhf"
},
say: () => {
console.log(this.name); // 因为箭头函数没this 所以使用上一层作用域中this this->window --->window.name===>yq
function fun2() {
console.log(this.name); // this-->window this.a =fun2 所以 this.a() ==window.a() -->console.log(this.name)==console.log(window.name)
}
this.a = fun2;
this.a();
},
fun: function() {
console.log(this.name); // this 在普通函数;obj.name===>yan
// var a = a=>console.log(this.name)
var a = a => {
return console.log(this.name); // this箭头函数;this--》obj so ==>obj.name ==》yan
};
a();
return function() {
console.log(this.name); // this 在普通函数;window.name===>yq
};
}
};
// obj.say();
// obj.fun();
// var res = obj.fun()
// res() // this 值window
var obj = {
a: 1,
obj2: {
a: 2,
obj3: {
a: 3,
getA: () => {
console.log(this); // this ==>window
console.log(this.a); // window.a ==> undefined
}
}
}
};
obj.obj2.obj3.getA();
// 箭头函数无 constructor 属性;不能做构造函数。没有this
var b = (name, age, dec) => {
this.name = name;
this.age = age;
this.dec = dec;
};
var zhx = new b("zhx", 21, "真难啊");
console.log(zhx);
var name = "veb";
var obj = {
name: "len",
say: function() {
function fun() {
console.log(this.name); // obj.name
}
this.say = fun; // obj{name:'len',say:functin fun(){console.log(this.name)}}
this.say();
}
};
obj.say();
// var fn = obj.say;
// fn();
```js
// 构造函数中this,指向创建的对象
function Person(){
console.log(this);//这时this指向yyc构造函数对象
this.name = arguments[0]
}
var yyc = new Person('xxx');
Person();//这时this指向window
/ 创建一个对象,就是将构造函数的作用域赋给了新对象,所以this指向了这个对象,return {} [] function之后,改变了作用域,作用域赋值给了{} [] function 所以this指向{} [] function
function fn(){
this.name = '追梦人';
return {}
}
var a = new fn();
console.log(a.name);//undefined
// 构造函数this 默认
function fn1(){
this.name = 'aaa';
// return this //默认return 返回this 所以指向构造对象
}
var b = new fn1();