var name="window";
var obj = {
name:"objname",
sayHello:function(){
console.log(obj.name)//objname
// console.log(this);//obj
}
}
obj.sayHello();
"use strict"//严格模式下
function foo(){
console.log(this);
}
foo();//undefined
*/
//在普通模式下,普通函数,谁调用这个函数,this就指向谁
function foo(){
console.log(this);//window
}
foo();//全局函数可以看作是window的方法
var name="window";
var age1=20;
let age2=10;
console.log(window.age1);//20
console.log(window.age2);//undefined,let定义的不属于全局定义
var obj = {
name:"objname",
sayHello:function(){
console.log(this)
}
}
obj.sayHello();//obj对象
console.log(obj.name);//objname
var name="window";
var obj = {
name:"objname",
sayHello:function(){
return function(){
console.log(this)
}
}
}
obj.sayHello()();//window
上面相当于这个
var f=obj.sayHello();
obj.sayHello();//空
console.log(obj.sayHello());//输出函数体
var name="window";
var obj = {
name:"objname",
sayHello:function(){
setTimeout(function(){//setTimeout全局方法是window方法
console.log(this)
})
}
}
obj.sayHello();//window
箭头函数的this指向问题
箭头函数this指向定义这个箭头函数时所在环境中的this
在哪个地方定义就指向那个地方的this
var foo=()=>{
console.log(this);
}
foo();//window
var name="window";
var obj = {
name:"objname",
sayHello:()=>{
console.log(this)
}
}
obj.sayHello();//window
上面代码运行机制相当于
var obj={};
obj.name="onjname";
obj.sayHello=()=>{
console.log(this);
}
obj.sayHello();//window
var name="window";
var obj = {
name:"objname",
sayHello:function(){
return ()=>{
console.log(this)
}
}
}
obj.sayHello()();//obj
var name="window";
var obj = {
name:"objname",
sayHello:()=>{
console.log(this);
return ()=>{
console.log(this)
}
}
}
obj.sayHello()();//window
var name = "window";
var obj = {
name: "objname",
sayHello: function() {
setTimeout( () => {
console.log(this)
})
}
}
obj.sayHello(); //obj
//call apply bind改变this指向
var obj1={
name:"obj1",
sayHello:function(a){
console.log(this.name);
console.log(a)
}
}
var obj2={
name:"obj2"
}
obj1.sayHello.call(obj2,10);//obj2 10改变了this指向,指向call
obj1.sayHello.apply(obj2,[20])//obj2 20改变了this指向,指向apply
obj1.sayHello.bind(obj2)(30);//obj2 30改变了this指向,指向bind
//取数组中的最大值最小值,及其索引
var arr=[11,57,0,-2];
var min=Math.min.apply(null,arr);//不改变原数组
console.log(min);//-2
console.log(arr.indexOf(min));//3