执行域
var a = "123"
function test1() {
var a = '345'
test2()
}
function test2() {
console.log(a)
}
test2()
function foo() {
var a = b = 10
}
foo()
console.log(b)
console.log(a)
this绑定规则: 与调用方式相关,与定义方式无关
function foo1() {
console.log(this)
}
foo1()
function test() {
console.log(this)
}
const obj = {
a: "name",
b: test
}
obj.b()
function foo1() {console.log(this)}
foo.bind("abc").call("efg")
function foo() {
console.log(this)
}
const obj = {
name: 'obj',
foo: foo.bind("aaa")
}
obj.foo()
const obj = {
name: "obj",
foo: function() {
console.log(this)
}
}
const res = new obj.foo()
function foo3() {
console.log(this)
}
const bar3 = foo3.bind("aaa")
const obj3 = new bar3()
this特殊处理
function foo() {
console.log(this)
}
foo.apply(null)
foo.apply(undefined)
const obj1 = {
name: "obj1",
foo: function() {
console.log(this.name)
}
}
const obj2 = {
name : "obj2"
}
obj2.bar = obj1.foo
obj2.bar();
(obj2.baf)()
(obj2.bar = obj1.foo)()
箭头函数
const obj = {
data: [],
getData: function() {
const _this = this
setTimeout(function() {
console.log(this.data)
})
setTimeout(() => {
console.log(this.data)
})
}
}
obj.getData()
this面试题
面试题1
var name = 'window'
var person1 = {
name: 'person1',
foo1: function() {
console.log(this.name)
},
foo2: () => console.log(this.name),
foo3: function() {
return function() {
console.log(this.name)
}
},
foo4: function() {
console.log(this)
return () => {
console.log(this.name)
}
}
}
var person2 = {name: 'person2'}
person1.foo1()
person1.foo1.call(person2)
person1.foo2()
person1.foo2.call(person2)
person1.foo3()()
person1.foo3.call(person2)()
person1.foo3().call(person2 )
person1.foo4()()
person1.foo4.call(person2)()
person1.foo4().call(person2)
面试题2
var name = "window"
function Person(name) {
this.name = name
this.foo1 = function() {
consol.elog(this.name)
}
this.foo2 = () => console.log(this.name)
this.foo3 = function() {
return function() {
console.log(this.name)
}
}
this.foo4 = function () {
return () => {
console.log(this.name)
}
}
}
var person1 = new Person("person1")
var person2 = new Person("person2")
person1.foo1()
person1.foo1.call(person2)
person1.foo2()
person1.foo2.call(person2)
person1.foo3()()
person1.foo3.call(person2)()
person1.foo3().call(person2)
person1.foo4()()
person1.foo4.call(person2)()
person1.foo4().call(person2)
面试题4
var name = 'window'
function Person (name) {
this.name = name
this.obj = {
name: 'obj',
foo1: function () {
return function () {
console.log(this.name)
}
},
foo2: function () {
return () => {
console.log(this.name)
}
}
}
}
var person1 = new Person('person1')
var person2 = new Person('person2')
person1.obj.foo1()()
person1.obj.foo1.call(person2)()
person1.obj.foo1().call(person2)
person1.obj.foo2()()
person1.obj.foo2.call(person2)()
person1.obj.foo2().call(person2)