面向对象的JavaScript-007-Function.prototype.bind() 的4种作用

1.

1 // Function.prototype.bind() 的作用
  2
  3     // 1.Creating a bound function
  4     this.x = 9;
  5     var module = {
  6       x: 81,
  7       getX: function() { return this.x; }
  8     };
  9
 10     console.log(module.getX()); // 81
 11
 12     var retrieveX = module.getX;
 13     console.log(retrieveX());
 14     // 9, because in this case, "this" refers
 15     // to the global object
 16
 17     // Create a new function with 'this' bound to module
 18     // New programmers might confuse the
 19     // global var x with module's property x
 20     var boundGetX = retrieveX.bind(module);
 21     console.log(boundGetX()); // 81
 22
 23     // 2.Partially applied functions
 24
 25     // The next simplest use of bind() is to make a function with pre-specified initial arguments. These arguments (if any) follow the provided this value and are then inserted at the start of the arguments passed to the target function, followed by the arguments passed to the bound function, whenever the bound function is called.

 26     function list() {
 27       return Array.prototype.slice.call(arguments);
 28     }
 29
 30     var list1 = list(1, 2, 3); // [1, 2, 3]
 31     console.log(list1);
 32     // Create a function with a preset leading argument
 33     var leadingThirtysevenList = list.bind(undefined, 37);
 34     console.log(leadingThirtysevenList);
 35     var list2 = leadingThirtysevenList();
 36     // [37]
 37     console.log(list2);
 38     var list3 = leadingThirtysevenList(1, 2, 3);
 39     // [37, 1, 2, 3]
 40     console.log(list3);
 41
 42     // 3.With setTimeout
 43
 44     //y default within window.setTimeout(), the this keyword will be set to the window (or global) object. When working with class methods that require this to refer to class instances, you may explicitly bind this to the callback function, in order to maintain the instance.

 45     function LateBloomer() {
 46       this.petalCount = Math.ceil(Math.random() * 12) + 1;
 47     }
 48
 49     // Declare bloom after a delay of 1 second
 50     LateBloomer.prototype.bloom = function() {
 51       window.setTimeout(this.declare.bind(this), 1000);
 52     };
 53
 54     LateBloomer.prototype.declare = function() {
 55       console.log('I am a beautiful flower with ' +
 56         this.petalCount + ' petals!');
 57     };
 58
 59     var flower = new LateBloomer();
 60     flower.bloom();
 61     // after 1 second, triggers the 'declare' method
 62
 63     // 3.Bound functions used as constructors
 64     // Bound functions are automatically suitable for use with the new operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided this is ignored. However, provided arguments are still prepended to the constructor call:
 65     function Point(x, y) {
 66       this.x = x;
 67       this.y = y;
 68     }
 69
 70     Point.prototype.toString = function() {
 71       return this.x + ',' + this.y;
 72     };
 73
 74     var p = new Point(1, 2);
 75     p.toString(); // '1,2'
 76
 77     // not supported in the polyfill below,
 78
 79     // works fine with native bind:
 80
 81     var YAxisPoint = Point.bind(null, 0/*x*/);
 82
 83
 84     var emptyObj = {};
 85     var YAxisPoint = Point.bind(emptyObj, 0/*x*/);
 86
 87     var axisPoint = new YAxisPoint(5);
 88     axisPoint.toString(); // '0,5'
 89
 90     console.log(axisPoint instanceof Point); // true
 91     console.log(axisPoint instanceof YAxisPoint); // true
 92     console.log(new Point(17, 42) instanceof YAxisPoint); // true
 93
 94     // Example can be run directly in your JavaScript console
 95     // ...continuing from above
 96
 97     // Can still be called as a normal function
 98     // (although usually this is undesired)
 99     console.log(YAxisPoint(13));
100
101     console.log(emptyObj.x + ',' + emptyObj.y);
102     // >  '0,13'
103
104     // 4.Creating shortcuts
105     var slice = Array.prototype.slice;
106
107     // ...

108
109     slice.apply(arguments);
110     // same as "slice" in the previous example
111     var unboundSlice = Array.prototype.slice;
112     var slice = Function.prototype.apply.bind(unboundSlice);
113
114     // ...

115
116     slice(arguments);
117
118     // Polyfill
119     // The bind function is an addition to ECMA-262, 5th edition; as such it may not be present in all browsers. You can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of bind() in implementations that do not natively support it.

120     if (!Function.prototype.bind) {
121       Function.prototype.bind = function(oThis) {
122         if (typeof this !== 'function') {
123           // closest thing possible to the ECMAScript 5
124           // internal IsCallable function
125           throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
126         }
127
128         var aArgs   = Array.prototype.slice.call(arguments, 1),
129             fToBind = this,
130             fNOP    = function() {},
131             fBound  = function() {
132               return fToBind.apply(this instanceof fNOP
133                      ? this
134                      : oThis,
135                      aArgs.concat(Array.prototype.slice.call(arguments)));
136             };
137
138         if (this.prototype) {
139           // Function.prototype doesn't have a prototype property
140           fNOP.prototype = this.prototype;
141         }
142         fBound.prototype = new fNOP();
143
144         return fBound;
145       };
146     }

面向对象的JavaScript-007-Function.prototype.bind() 的4种作用

You can do anything you set your mind to, man!

Original: https://www.cnblogs.com/shamgod/p/5523744.html
Author: shamgod
Title: 面向对象的JavaScript-007-Function.prototype.bind() 的4种作用

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/536423/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • DOM树:JavaScript是如何影响DOM树构建的

    在上一篇文章中,我们通过开发者工具中的网络面板,介绍了网络请求过程的几种性能指标以及对页面加载的影响。 而在渲染流水线中,后面的步骤都直接或者间接地依赖于 DOM 结构,所以本文我…

    JavaScript 2023年5月29日
    0112
  • 面向对象的JavaScript-008-Function介绍

    1. 1 // 函数 2 /* Declare the function 'myFunc' */ 3 function myFunc…

    JavaScript 2023年5月29日
    094
  • JavaScript进行WebSocket字节流通讯示例

    websocket进行通讯时,可以选择采用字符串或者字节流的传输模式。但在发送与接收时,需要考虑数据的分包,即分成一个个请求与响应消息。无论是采用哪种传输模式,都不免要遇到这个问题…

    JavaScript 2023年5月29日
    074
  • JavaScript 浮动定位提示效果

    本来想做一个集合浮动定位和鼠标跟随的tooltips效果,但发现定位和鼠标跟随在一些关键的地方还是不同的,还是分开来吧。这个效果本身难度不大,主要在程序结构和扩展中下了些功夫,务求…

    JavaScript 2023年5月29日
    075
  • 转:JavaScript函数式编程(三)

    这是完结篇了。 在第二篇文章里,我们介绍了 Maybe、Either、IO 等几种常见的 Functor,或许很多看完第二篇文章的人都会有疑惑: 『这些东西有什么卵用?』 事实上,…

    JavaScript 2023年5月29日
    074
  • javascript运行机制与原理

    本文将从浏览器进程,到浏览器内核运行,到JS引擎单线程,再到JS事件循环机制,系统梳理js的运行机制和原理,形成一个知识体系 区分进程和线程 线程和进程区分不清,是很多新手都会犯的…

    JavaScript 2023年5月29日
    079
  • Javascript正则分组命名

    Javascript的正则分组不支持命名,只好自己搞了一个。先把命名存入数组,然后匹配。 唉~~~有更好的解决方案么? 代码: javascript;gutter:false; v…

    JavaScript 2023年5月29日
    092
  • JavaScript高级用法二之内置对象

    对象的属性:反映该对象某些特定的性质的,如:字符串的长度、图像的长宽等; 对象的方法:能够在对象上执行的动作。例如,表单的”提交”(Submit),时间的&…

    JavaScript 2023年5月29日
    070
  • JavaScript, 函数是实现异步的基础

    Original: https://www.cnblogs.com/pssp/p/8869928.htmlAuthor: 追梦子Title: JavaScript, 函数是实现异步…

    JavaScript 2023年5月29日
    054
  • MathJax — A JavaScript display engine for mathematics that works in all browsers.

    MathJax https://www.mathjax.org/ web页面上的数学公式显示引擎。 使用纯web技术css等 支持多种输入格式: MathML Tex asciim…

    JavaScript 2023年5月29日
    073
  • JavaScript之Blob对象基本用法及分片上传示例

    Blob基本用法 通过Blob的构造函数创建Blob对象: blobParts: 数组类型, 数组中的每一项连接起来构成Blob对象的数据,数组中的每项元素可以是 ArrayBuf…

    JavaScript 2023年5月29日
    066
  • 把C编译成javascript的方法

    把C编译成javascript的方法 把C编译成javascript的方法,便于嵌入到HTML5中 https://github.com/kripken/emscripten Or…

    JavaScript 2023年5月29日
    064
  • JavaScript的OOP编程2

    我做了一个observer的设计模式实现 version1 // ————————————————– functi…

    JavaScript 2023年5月29日
    079
  • JavaScript 日期联动选择器

    一个日期联动选择器,年月日联动显示,准确显示日期(包括闰年日期),可自定义日期范围。 效果预览: 年 月 日你选择的日期: 程序说明 【select】 先说清空一个select,最…

    JavaScript 2023年5月29日
    052
  • 关于javascript 正则中连续执行返回null的问题

    最近在使用javascript 判断是否是手机浏览器中遇到一个问题 发现先使用test判断是否匹配,再使用exec获取id时,尽然返回为null。如果再前面执行一次exec,再执行…

    JavaScript 2023年5月29日
    0100
  • JavaScript 滑移效果

    这里说的滑移其实就是减速效果,能根据设定的坐标平面移动。 效果 自动滑移: 定点滑移:(鼠标点击) 定线滑移:(鼠标拖动轨迹) 代码: DOCTYPE html PUBLIC &#…

    JavaScript 2023年5月29日
    066
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球