// 非严格模式下function hello() { console.log(this) // this 指向 window}hello()

'use strict'function hello() { console.log(this) // undefined}hello()// 不要依赖函数内部的 this
// 谁调用了这个函数,this 就是谁const obj = { name: 'haru', hello: function () { console.log(this.name + 'haha') }}obj.hello()

// window.name 有值// 'use strict' : // use strict 情况下 hello1() 点用 打印 console.log(this.myName) 会出现如下错误// Uncaught TypeError: Cannot read properties of undefined (reading 'myName')const obj = { myName: 'haru', hello: function () { console.log(this.myName + 'haha') // undefined }}let hello1 = obj.hello() // TODO WHYhello1() // 虽然函数赋值了 obj.hello(), 调用时 hello() 自己调用, 没有 obj. 开头, 失去了绑定关系
const obj = { myName: 'haru', hello: function() { console.log('params', argument) console.log(this.myName + 'haha') // haru haha }}let hello1 = obj.hello()hello1()// 可以用 call / apply 来改变函数内部的 thishello1.call(obj, 345, 456)hello1.apply(obj, [345, 456])let hello2 = hello1.bind(obj)hello2(123)
// dom 操作<body> <button id='app' data-name='haru'>btn</button> <script> document.querySelector('#app').addEventListener('click', function() { console.log(this) // <button id='app' data-name='haru'>btn</button> this.innerText = 'xx' console.log(this.getAttribute('data-name')) }, false) <script></body>
let obj = {
myName = 'haru',
hello: function () {
// const self = this // TODO WHY
// function demo () {
// console.log(self.myName + 'haha') // haru
// }
function demo() {
console.log(this.myName + 'haha') // undefined
}
demo()
}
}
// 箭头函数 没有 arguments, 没有 this
let obj = {
myName = 'haru',
hello: function() {
const demo = () => {
console.log(this.myName + 'haha') // haru
}
demo()
}
}
obj.hello()
const test1 = (a, b, c = 1) {
console.log( a + b)
// 箭头函数不需要写 return 关键字
// return a*2
}
const test2 = item => item*2