javascript 中 function bind()

Function bind() and currying

<%--

All JavaScript functions have a method called bind that binds to an object and returns a new function. The first argument to bind sets the this context of the function.

function area (height) {
    return this.width * height;
}
var obj = { width : 5 };
var bound = area.bind(obj);
alert(bound(4));             // => 20

  

Calling bound(4); invokes the original function area as a method of obj, like obj.area(4);. The argument you pass tobound is passed as the height argument to the function area.

In addition to binding a function to an object,--%>

EcmaScript 5 supports a bind method that brings native currying to JavaScript. You no longer need to use a curry helper function. The arbitrary number of arguments that you pass to bind are also bound.

function add(x, y, z) {
    return x + y + z;
}
var partial = add.bind(null, 1, 2); 

var result = partial(3);              // pass 3 for the z argument
alert(result);                        // => 6

  

This creates a new function called partial. The this value is bound to null, i.e. the global object, and the x and yarguments are bound to 1 and 2 respectively. Calling partial with the argument value 3 binds this value to z and then executes the add function without the need to write a curry function.

-------------------------------------------------------------------------------

JavaScript: Passing by Value or by Reference

In JavaScript, we have functions and we have arguments that we pass into those functions. But how JavaScript handles what you’re passing in is not always clear. When you start getting into object-oriented development, you may find yourself perplexed over why you have access to values sometimes but not other times.

When passing in a primitive type variable like a string or a number, the value is passed in by value. This means that any changes to that variable while in the function are completely separate from anything that happens outside the function. Let’s take a look at the following example:

function myfunction(x)
{
      // x is equal to 4
      x = 5;
      // x is now equal to 5
}

var x = 4;
alert(x); // x is equal to 4
myfunction(x);
alert(x); // x is still equal to 4

Passing in an object, however, passes it in by reference. In this case, any property of that object is accessible within the function. Let’s take a look at another example:

function myobject()
{
	this.value = 5;
}
var o = new myobject();
alert(o.value); // o.value = 5
function objectchanger(fnc)
{
	fnc.value = 6;
}
objectchanger(o);
alert(o.value); // o.value is now equal to 6

So, what happens when you pass in a method of an object? Most would expect (or at least I did) that it would be passed by reference allowing the method to access other parts of the object it is apart of. Unfortunately, that’s not the case. Check out this example:

function myobject()
{
	this.value = 5;
}
myobject.prototype.add = function()
{
	this.value++;
}
var o = new myobject();
alert(o.value); // o.value = 5
o.add();
alert(o.value); // o.value = 6
function objectchanger(fnc)
{
	fnc(); // runs the function being passed in
}
objectchanger(o.add);
alert(o.value); // sorry, still just 6

The problem here is the use of the ‘this’ keyword. It’s a handy short-hand for referring to the current object context. When passing a function as a parameter, though, the context is lost. More accurately, this now refers to the context of the object making the call instead of the object’s function we just passed in. For standalone functions, this would be the window object and for functions called from an event, this would be the event object.

Solving the problem

There are two possible ways to get around this.

Option 1: When you know the method

If you know the method of the object that will be called then it’s fairly easy. Just pass in the object instead of the function and call that instead. Using theobjectchanger from the last example you’d get the following:

function objectchanger(obj)
{
	obj.add(); // runs the method of the object being passed in
}
objectchanger(o);
alert(o.value); // the value is now 7

Option 2: When you don’t know the method

If you don’t know the method of the object being passed in then you need to pass both the method and the object as parameters and use the call method. callis part of the JavaScript specification and allows a function to run in the context of another object. As a result, the this keyword will reference the right object: the object we passed in.

Here’s our objectchanger function one more time:

function objectchanger(fnc, obj)
{
	fnc.call(obj); // runs the method of the object being passed in
}
objectchanger(o.add, o);
alert(o.value); // the value is now 7

Happy Scripting!

PUBLISHED JANUARY 18, 2006 · UPDATED SEPTEMBER 14, 2006

CATEGORIZED AS JAVASCRIPT

SHORT URL: https://snook.ca/s/503

时间: 2024-10-19 04:37:05

javascript 中 function bind()的相关文章

JavaScript中的bind,call和apply函数的用法和区别

一直没怎么使用过JavaScript中的bind,call和apply, 今天看到一篇比较好的文章,觉得讲的比较透彻,所以记录和总结如下 首先要理解的第一个概念,JavaScript中函数调用的方式,总结下来,有以下4种 1. 方法调用 2. 正常函数调用 3. 构造器函数调用 4. apply/call 调用 要明白的第2个概念, JavaScript 中的函数,无论是上面哪种函数调用方式,除了你函数声明时定义的形参外,还会自动给函数添加两个形参,分别是this 和 arguments 要明白

javascript中(function($){...})(jQuery)写法是什么意思

在javascript中 (function($){...})(jQuery)的写法是什么意思. ======================================================================   //这是一条分割线. 首先 function(arg){ //.... } 这种形式的在javascript中称之为匿名函数.arg则是匿名函数的参数. 而(function($){ })(jQuery);这种形式则是执行匿名函数并且传递参数jQuery.

Javascript中Function declarations 理解

首先来看一段代码: 1.f = function() {return true;}; 2.g = function() {return false;}; 3.(function() { 4. if (g() && [] == ![]) { 5. f = function f() {return false;}; 6. function g() {return true;} 7. } 8.})(); 9.console.log(f()); 理解上面这段code有几个关键点: 第4行code的

全面理解Javascript中Function对象的属性和方法

函数是 JavaScript 中的基本数据类型,在函数这个对象上定义了一些属性和方法,下面我们逐一来介绍这些属性和方法,这对于理解Javascript的继承机制具有一定的帮助. 属性(Properties) arguments 获取当前正在执行的 Function 对象的所有参数,是一个类似数组但不是数组的对象,说它类似数组是因为其具有数组一样的访问性质及方式,可以由arguments[n]来访问对应的单个参数的值,并拥有数组长度属性length.还有就是arguments对象存储的是实际传递给

Javascript中的Bind 、Call和Apply

看以下代码: var bind = Function.prototype.call.bind(Function.prototype.bind); 第一眼看上去,我能猜出它究竟是用来做什么的.它把x.y(z)转化成了y(x,z). 编写良好的代码会比较容易被读懂.在读完Functional Javascript和 JavaScript Allongé (两本都是相当好的书)这两本书之后,再加上在Javascript函数式编程方面有些经验,弄懂上面这段代码的意思毫无压力.但是应该怎么向没有函数式编程

JavaScript中Function的拓展

Function 是什么东西,就是JavaScript中的顶级类,系统级别的类.我们平时写的函数方法例如下. function Animal() { } Animal就是Function的实例,但是在我们的逻辑中 Animal是类,是自定义类. Function是类,Animal是类也是实例,Animal是Function的实例,Animal是自定义类.这点大家一定要搞清楚. 我们在顶级类上定义一个method的方法,用于进行键值对的方式进行方法链式的设定, Function.prototype

JavaScript中Function函数与Object对象的关系

函数对象和其他内部对象的关系 除了函数对象,还有很多内部对象,比如:Object.Array.Date.RegExp.Math.Error.这些名称实际上表示一个 类型,可以通过new操作符返回一个对象.然而函数对象和其他对象不同,当用typeof得到一个函数对象的类型时,它仍然会返回字符串 "function",而typeof一个数组对象或其他的对象时,它会返回字符串"object".下面的代码示例了typeof不同类型的情况: 以下是引用片段: alert(ty

JavaScript中function的多义性

JavaScript 中的 function 有多重意义.它可能是一个构造器(constructor),承担起对象模板的作用: 可能是对象的方法(method),负责向对象发送消息.还可能是函数,没错是函数,和对象没有任何关系独立存在的可以被调用的函数. 由于语言设计者的妥协,在 JavaScript 加入了一些 class 相关的特性,以使 JavaScript 看起来确实象 Java,可以 “面向对象”.虽然 JavaScript 添加了 new 和 this, 但却没有 class (ES

javascript 中function(){},new function(),new Function(),Function 简单介绍

函数是JavaScript中很重要的一个语言元素,并且提供了一个function关键字和内置对象Function,下面是其可能的用法和它们之间的关系. function使用方式 var foo01 = function() //或 function foo01() { var temp = 100; this.temp = 200; return temp + this.temp; } alert(typeof(foo01)); // function alert(foo01()); // 30