Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第58题(2019-10-15):定义一个log方法,让它可以代理console.log的方法 #60

Open
qappleh opened this issue Oct 15, 2019 · 1 comment
Labels

Comments

@qappleh
Copy link
Owner

qappleh commented Oct 15, 2019

No description provided.

@qappleh
Copy link
Owner Author

qappleh commented Oct 16, 2019

可行的方法一:

function log(msg) {
  console.log(msg);
}
log("hello world!") // hello world!  

如果要传入多个参数呢?显然上面的方法不能满足要求,所以更好的方法是:

function log() {  
  console.log.apply(console, arguments);
};  

到此,追问apply和call方法的异同。

答案:

对于apply和call两者在作用上是相同的,即是调用一个对象的一个方法,以另一个对象替换当前对象。将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。

但两者在参数上有区别的。对于第一个参数意义都一样,但对第二个参数: apply传入的是一个参数数组,也就是将多个参数组合成为一个数组传入,而call则作为call的参数传入(从第二个参数开始)。 如 func.call(func1,var1,var2,var3)对应的apply写法为:func.apply(func1,[var1,var2,var3]) 。

@qappleh qappleh added the js label Nov 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant