javaScript ES6 - call,apply,bind 修改this指向,开启严格模式
1.call与apply
call与apply都是执行一次修改的方法,不过apply的第二个参数为数组格式
//构造函数 function Human(id,name) { this.id=id; this.name=name; } //方法 function info(args){ console.log(args) console.log(this); } //call info.call(Human,"leviAckerman"); //bind info.bind(Human,["levi","leviAckerman"]);
要修改的方法.call 第一个参数为执行的类,第二个参数为要修改方法的值
要修改的方法.bind 第一个参数为执行的类,第二个参数为要修改方法的数组
2.bind
不会执行一次方法,会返回一个this被改变之后了的方法
//构造函数 function Human(id,name) { this.id=id; this.name=name; } //方法 function info(args){ console.log(args) console.log(this); } //bind 返回this执行被改变之后了的方法 var newInfo=info.bind(Human,"levi"); newInfo(); //levi Human构造函数
3.开启严格模式
<script> //开启严格模式 "use strict" </script> <script> function info() { //为某个函数开启严格模式 "use strict" } </script>
posted on 2023-02-08 13:38 Mikasa-Ackerman 阅读(47) 评论(0) 编辑 收藏 举报