javascript自定义范围绑定功能 [英] javascript custom scope binding function
问题描述
我正在阅读本文- http://www.robertsosinski.com/2009/04/28/binding-scope-in-javascript/ -创建自定义绑定函数的地方.
I am reading this article - http://www.robertsosinski.com/2009/04/28/binding-scope-in-javascript/ - where a custom bind function is made.
Function.prototype.bind = function(scope) {
var _function = this;
return function() {
return _function.apply(scope, arguments);
}
}
alice = {
name: "alice"
}
eve = {
talk: function(greeting) {
console.log(greeting + ", my name is " + this.name);
}.bind(alice) // <- bound to "alice"
}
eve.talk("hello");
// hello, my name is alice
我的问题是这条线特别是
My question is this line in particlar
return function() {
return _function.apply(scope, arguments);
}
为什么在_function.apply(作用域,参数)中返回;那里?它在做什么以及正在返回什么?我删除了该退货,但仍然有效.
Why is the return in _function.apply(scope, arguments); there? And what is it doing and what is being returned? I removed that return and it still works.
推荐答案
Why is the return in _function.apply(scope, arguments); there? And what is it doing and what is being returned? I removed that return and it still works.
这是您要返回值的地方.当前,您的talk函数没有返回任何值,因此您不需要它.如果您将通话功能更改为
This is there in case you want to return a value. Currently your talk function is not returning any value so you don't need it. if you change your talk function to
eve = {
talk: function(greeting) {
return ( greeting + ", my name is " + this.name) ;
}.bind(alice) // <- bound to "alice"
}
console.log(eve.talk("hello"));
现在您将了解为什么需要退货
Now you will realize why return is required
这篇关于javascript自定义范围绑定功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!