转载请注明出处
bind()
bind()
方法建立一个新的函数,在bind()
被调用时,这个新函数的this
被bind的第一个参数指定,其他的参数将做为新函数的参数供调用时使用。数组
function.bind(thisArg[,arg1[,arg2[, ...]]])
var module = { x: 42, getX: function() { return this.x; } } var unboundGetX = module.getX; console.log(unboundGetX()); // The function gets invoked at the global scope // expected output: undefined var boundGetX = unboundGetX.bind(module); console.log(boundGetX()); // expected output: 42
bind()
的一个实现:Function.prototype.bind = function(context) { if (typeof this !== 'function') { throw new TypeError('Error') } let _this = this let args = [...arguments].slice(1) return function F() { // 判断是否被当作构造函数使用 if (this instanceof F) { return _this.apply(this, args.concat([...arguments])) } return _this.apply(context, args.concat([...arguments])) } }
apply()
apply()
方法调用一个具备给定this
值的函数,以及做为一个数组(或相似数组对象)提供的参数。app
func.apply(thisArg, [argsArray])
var numbers = [5, 6, 2, 3, 7]; var max = Math.max.apply(null, numbers); console.log(max); // expected output: 7 var min = Math.min.apply(null, numbers); console.log(min); // expected output: 2
apply()
的一个实现:Function.prototype.apply = function(context) { // context就是apply的第一个参数,在这里也就是obj // 判断是不是undefined和null if (typeof context === 'undefined' || context === null) { context = window } // this也就是调用apply的函数 把函数赋值给context下面的一个键,这里是fn context.fn = this // arguments就是传进来的参数 let args = arguments[1] let result if (args) { result = context.fn(...args) } else { result = context.fn() } delete context.fn return result } let test = function (sex) { console.log(this.name + sex) } let obj = { name: '我是' } test.apply(obj, ['test'])
call()
call()
方法使用一个指定的 this
值和单独给出的一个或多个参数来调用一个函数。函数
fun.call(thisArg, arg1, arg2, ...)
function Product(name, price) { this.name = name; this.price = price; } function Food(name, price) { Product.call(this, name, price); this.category = 'food'; } console.log(new Food('cheese', 5).name); // expected output: "cheese"
call()
的一个实现:Function.prototype.call = function(context) { // context就是call的第一个参数,在这里也就是obj // 判断是不是undefined和null if (typeof context === 'undefined' || context === null) { context = window } // this也就是调用call的函数 把函数赋值给context下面的一个键,这里是fn context.fn = this // arguments就是传进来的参数 let args = [...arguments].slice(1) let result = context.fn(...args) delete context.fn return result } let test = function (sex) { console.log(this.name + sex) } let obj = { name: '我是' } test.call(obj, 'test')
欢迎浏览个人 我的网站