js函数实现自己实现call和apply函数

2020-10-29  本文已影响0人  奋斗的小鸟cx

1 call和apply是怎样使用的?
call函数接收多个参数,第一个参数是this的指向,之后的参数都是函数的参数,apply方法接收两个参数,第一个参数是this的指向,第一个参数,是函数参数组成的数组,在es6之前,可以用apply给函数传入参数数组

eg:
var person = {
  fullName: function(txt) {
     console.log(txt + this.firstName + " " + this.lastName);
   }
 }
var person1 = {
   firstName:"John",
   lastName: "Doe"
} 
person.fullName.call(person1, "Hello, ");  // 输出"Hello, John Doe"

call做了什么主要分三步

手动写call方法

Function.prototype.myCall=function(context){
 context.fn=this || window
var result=cntext.fn()
return result
}
var person = {
  fullName: function(txt,s) {
     console.log(txt + s+this.firstName + " " + this.lastName);
   }
 }
var person1 = {
   firstName:"John",
   lastName: "Doe"
} 
Function.prototype.myCall=function(context,...args){
 context.fn=this || window
var result=context.fn(...args)
return result
}
person.fullName.myCall(person1, "Hello","wode");

手动写apply

Function.prototype.myApply=function(context,args){
 context.fn=this || window
args=args || []
var result=context.fn(...args) 
//console.log(...[1, 2, 3])
// 1 2 3
return result
}

调用:person.fullName.myApply(person1, ["Hello","wode"]);

对于person来说,我们的代码并没有更改任何属性或者方法。但对于person1,我们增加了一个fn方法,因此,要把这个方法在运行之后删掉:

delete context.fn;

深入理解Object.prototype.toString.call()

数据类型 列子 return
字符串 "foo".toString() "foo"
数字 1.toString() Uncaught SyntaxError: Invalid or unexpected token
布尔值 false.toString() "false"
undefined undefined.toString() Uncaught TypeError: Cannot read property 'toString' of undefined
null null.toString() Uncaught TypeError: Cannot read property 'toString' of null
String String.toString() "function String() { [native code] }"
Number Number.toString() "function Number() { [native code] }"
Boolean Boolean.toString() "function Boolean() { [native code] }"
Array Array.toString() "function Array() { [native code] }"
Function Function.toString() "function Function() { [native code] }"
Date Date.toString() "function Date() { [native code] }"
RegExp RegExp.toString() "function RegExp() { [native code] }"
Error Error.toString() "function Error() { [native code] }"
Promise Promise.toString() "function Promise() { [native code] }"
Obejct Object.toString() "function Object() { [native code] }"
Math Math.toString() "[object Math]"

为什么会出现下面的情况?

Object.toString.call(Array)//"function Array() { [native code] }"
Object.prototype.toString.call(Array)//"[object Function]"

答案

Object.toString() // “function Object(){ [native code] }”
Object.prototype.toString() //" [object Object] "

需要注意的是:Math.toString()直接返回"[object Math]"。
Object对象和它的原型链上各自有一个toString()方法,第一个返回的是一个函数,第二个返回的是值类型。
因为Array,Function,Date虽然是基于Object进行创建的,但是他们继承的是Object.toString(),而不是Object.prototype.toString()。

判断一个对象是否为数组

var obj=[1,2]; Object.prototype.toString.call(obj) // [object Arrary]

上一篇 下一篇

猜你喜欢

热点阅读