函数之前的写法
var b = function (a) { console.log(a) } b(3)箭头函数写法
var b = (a) => { console.log(a) } b(3)箭头函数的简写, 参数一个可选择 “当只有一个参数是,参数的括号可以去掉,也可以不去掉” 没有参数加括号 参数多个逗号分隔(a,b,c)
var b = a => { console.log(a) } b(3)小tips: 箭头函数是一个匿名函数
Js中的 this 值 是在运行的时候才绑定的
const changhao = { name: "changhao", hobby: ["playgame", "singing", "running"], age: 21, printhobbies: function () { console.log(this)//此时应该指向的是changhao这个对象 this.hobby.map (function (hobby) { //这里函数是一个独立的函数,这个this指向 window 这个对象,所以是空的 console.log(`${this.name}${hobby}`); }) } } changhao.printhobbies() //这里是changhao调用的时候this 绑定 changhao的输出 : 发现是没有name的
const changhao = { name: "changhao", hobby: ["playgame", "singing", "running"], age: 21, printhobbies: function () { this.hobby.map((hobby) => { console.log(`${this.name} ${hobby}`); }) } } changhao.printhobbies()箭头函数的this值,是指向父级的作用域,
经典写法:
<script> let add = function (a, b) { a = a || 5; b = b || 8; return console.log(a + b) } add() </script>输出: ES6写法 嘻嘻,边学便用,用到了默认参数,参数简写,隐身返回,
<script> let add = (a = 5, b = 8) => console.log(a + b) add() </script>花式调用哈哈哈
<script> let add = (a=5, b = 8) => console.log(a + b) add(,b) </script>翻车 更正
<script> let add = (a=3, b=5) => console.log(a + b) add(undefined,15) </script>输出
报错,说person 不是一个构造器,因为 箭头函数不存在this值的绑定
这个时候this是指向window的 所以只能使用原来的构造函数方式function
let person = function (name, age) { this.name = name; this.age = age; } let bill = new person("bill", 20) console.log(bill)输出: 这样就正常的啦 今天把之前用的 prototype 了解了,之前Vue.prototype.axios = axios 不知是什么东西
原来 prototype 属性使您有能力向对象添加属性和方法。
<script> let person = function (name, age) { this.name = name; this.age = age; } let bill = new person("bill", 20) console.log(bill) person.prototype.money = 2000; console.log(bill.money) </script>还是一样的,箭头函数没有this绑定,箭头函数的this指向外层的 也就是window
回归正常写法,这个this 就指向 (动态绑定)运行他的那个东西 obox
<script> var obox = document.querySelector(".box") obox.onclick = function() { this.classList.add("add") // } </script>