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!
javascript 中 function bind()的更多相关文章
- JavaScript中的bind,call和apply函数的用法和区别
一直没怎么使用过JavaScript中的bind,call和apply, 今天看到一篇比较好的文章,觉得讲的比较透彻,所以记录和总结如下 首先要理解的第一个概念,JavaScript中函数调用的方式, ...
- Javascript中Function,Object,Prototypes,__proto__等概念详解
http://anykoro.sinaapp.com/2012/01/31/javascript%E4%B8%ADfunctionobjectprototypes__proto__%E7%AD%89% ...
- 转载 javascript中(function($){...})(jQuery)写法是什么意思
javascript中(function($){...})(jQuery)写法是什么意思 这里实际上是匿名函数function(arg){...}这就定义了一个匿名函数,参数为arg 而调用函数 ...
- javascript中 (function(){})();如何理解?
javascript中 (function(){})();如何理解? javascript中: (function(){})()是匿名函数,主要利用函数内的变量作用域,避免产生全局变量,影响整体页面环 ...
- 全面理解Javascript中Function对象的属性和方法
http://www.cnblogs.com/liontone/p/3970420.html 函数是 JavaScript 中的基本数据类型,在函数这个对象上定义了一些属性和方法,下面我们逐一来介绍这 ...
- Javascript中的Bind 、Call和Apply
看以下代码: var bind = Function.prototype.call.bind(Function.prototype.bind); 第一眼看上去,我能猜出它究竟是用来做什么的.它把x.y ...
- 把玩Javascript中的bind
前言 今天闲着无聊随便逛了逛MDN,忽而看到一个方法Function.prototype.bind(),突然发现除了使用这个方法之外都没有仔细琢磨过这个方法.于是乎,找到了kill time的事情-写 ...
- Javascript中的bind详解
前言 用过React的同学都知道,经常会使用bind来绑定this. import React, { Component } from 'react'; class TodoItem extends ...
- JavaScript中的bind方法及其常见应用
一.bind()方法的实现 在JavaScript中,方法往往涉及到上下文,也就是this,因此往往不能直接引用.就拿最常见的console.log("info…")来说,避免书写 ...
随机推荐
- Qt 5简介
Qt 5简介 Qt 5概要介绍 在Qt 5这个版本中,Qt Quick成为了Qt的核心.但是Qt 5也继续提供了本地C++强大的功能来完成更好的用户体验,也提供了对OpenGL/OpenGL ES图形 ...
- WampServer 下载以及安装问题
WampServer 3.0 下载: http://dl.pconline.com.cn/download/52877-1.html 碰到的问题DDL无法添加,解决方法: http://jingyan ...
- 【java】基础中的杂乱总结(一)
1 构造代码块 作用:给对象进行初始化.对象一建立就运行,并且优先于构造函数执行 构造函数是给所有对象进行统一初始化,构造函数是给对应的对象初始化 package package1; class Pe ...
- 华哥倒酒<区间标记,二分>
题目链接 #include<cstdio> #include<cstring> #include<algorithm> using namespace std; t ...
- ListView的淡入淡出和Activity的淡入淡出补间动画效果Animation
//=========主页面======================= package com.bw.lianxi7; import android.os.Bundle;import androi ...
- 3d 人物残像
前言: gameunity 框架 还在继续完善中,0.2版本将会是一次 重大的里程碑. 正文: 哈哈,大家一定流汗了吧.请原谅我为自己代言. 好了,今天我要讲的是 3d人物残像. 首先我来说下 目前 ...
- 使用过滤器(Filter)解决请求参数中文乱码问题(复杂方式)
前述: 在写这篇笔记之前,对笔记中的设计模式进行介绍: 本篇笔记中将要使用到的设计模式是:装饰(包装)设计模式 (1)装饰(包装)设计模式口诀: ...
- asp 特殊字符替换
<%Function specialstr(yourstring)find= "¿,À,Á,Â,Ã,Ä,Å,Æ,Ç,È,É,Ê,Ë,Ì,Í,Î,Ï,Ð,Ñ,Ò,Ó,Ô,Õ,Ö,Ø,Ù, ...
- 动态规划2-----hdu1069
首先这道题目先要理解题目的意思. 用一些方块堆塔,给出的每种方块个数是无限的,只有满足长宽都小于下面一个方块的方块才能摆上去. 首先这道题需要一个转化. 每个方块有3个不同的面,每个面长宽交换,一共每 ...
- 【转】你必须了解的Session的本质
有一点我们必须承认,大多数web应用程序都离不开session的使用.这篇文章将会结合php以及http协议来分析如何建立一个安全的会话管理机制.我们先简单的了解一些http的知识,从而理解该协议的无 ...