javascript 笔记——bind 用法小技巧

时间:2023-02-17 12:21:56
$(function(){

                //代码阅读能力
function speak(name){
return "Hello " + name;
} //此处写代码 //方法一
         //重点是bind的第二个参数会直接插入到callback的参数列表的第一个位置。
          Function.prototype.wrap = function(callback) { return callback.bind(this, this); }; 
         
//方法二
          /*speak.wrap = function(callback){
var _this = this;
return function a(yourName, myName){ return callback(_this, yourName, myName); }
}*/
          
          
speak = speak.wrap(function(original, yourName, myName){
                   var greeting = original(yourName);
return greeting + ", my name is " + myName;
}) //console.log(speak) var greeting = speak("Mary", "Kate"); console.log(greeting); })