From 37be50f0c7cd8c5d0919943ffc2302e3f9506174 Mon Sep 17 00:00:00 2001 From: weishuping Date: Thu, 30 Aug 2018 10:34:00 +0800 Subject: [PATCH] =?UTF-8?q?bind=E9=97=AE=E9=A2=98=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- somequestion.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 somequestion.js diff --git a/somequestion.js b/somequestion.js new file mode 100644 index 00000000..b56ee502 --- /dev/null +++ b/somequestion.js @@ -0,0 +1,33 @@ +//您好 最近很认真的再看你写的深入系列。在bind时候 发现了一个问题 +var obj = { + value: '123' +} +function bar(name, age) { + return { + name: name, + age: age, + value: this.value + } +} +// 第四版 +Function.prototype.bind2 = function (context) { + + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + + var fNOP = function () {}; + + var fbound = function () { + var bindArgs = Array.prototype.slice.call(arguments); + self.apply(this instanceof self ? this : context, args.concat(bindArgs)); + } + fNOP.prototype = this.prototype; + fbound.prototype = new fNOP(); + return fbound; + +} + +bar.bind2(obj)() //undefined +bar.bind(obj)() //{name: undefined, age: undefined, value: "123"} + +//两者结果有差异,其原因是在fbound中实现之后,没有返回该函数。如有考虑不正确的地方,还望指正 \ No newline at end of file