博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
bind/new/instanceof/assign模拟实现
阅读量:7107 次
发布时间:2019-06-28

本文共 1986 字,大约阅读时间需要 6 分钟。

Function.prototype.bind2 = function(context) {    const args = Array.prototype.slice.call(arguments, 1); // 获取除绑定的this参数之外的其他参数    const self = this;    var fBind = function() {        return self.apply(this instance fBind ? this : context, args.concat(Array.prototype.slice.call(arguments)));         // this instance fBind ? this : context为判断fBind是否作为构造函数调用,如果是则将this指向实例,否则this指向context参数。    }    fBind.prototype = Object.create(self.prototype);    return fBind;}复制代码

// new 为关键字,只模拟功能实现,不模拟具体调用,最后调用为new2(constructor, params1, params1);function new2() {    var constructor = Array.prototype.shift(arguments); // 获取构造函数,并且shift会改变arguments    var obj = new Object();    obj.__proto__ = constructor.prototype; // 加入原型链    var result = constructor.apply(obj, arguments);    return typeof result === 'object' ? result : obj; // 构造如果显示return一个对象,则返回该对象,否则返回this;}复制代码

// instanceof(x, y)function instanceof(x, y) {    while(x.__proto__!==null) {      if(x.__proto__===y.prototype) {          return true;          break;      }      x.__proto__ = x.__proto__.proto__;    }    if(x.__proto__==null) {
return false;}}复制代码

// Object.assignObject.defineProperty(Object, assgin2, {    wirte: true,    configurable: true,    enumerable: false,    value(target) {        if (target == null) throw new TypeError('Cannot convert undefined or null to object');        const results = typeOf target === 'Object' ? target : Object(target);        if (arguments.length > 1) {            for (let i = 1; i < arguments.length; i += 1) {                const arg = arguments[i];                if (arg !== null) {                    const obj = typeOf arg === 'Object' || 'Function' ? arg : Object(arg); // 简单类型会被包装成对象类型                    for (const k in obj) {                        if (Object.prototype.hasOwnProperty(obj, k)) {                            results[k] = obj[k]                        }                    }                }            }        }        return results;    }})复制代码

转载地址:http://qqjhl.baihongyu.com/

你可能感兴趣的文章
nginx
查看>>
明目张胆的抄袭者
查看>>
OpenResty(nginx扩展)实现防cc攻击
查看>>
Struts2 学习系列 (4) ValueStack和OGNL
查看>>
H2数据库使用
查看>>
转一篇文章:MySQL 通过idb文件恢复Innodb 数据
查看>>
Class<T>和Class<?>之间有什么区别
查看>>
java开发手册
查看>>
002SilverFox的介绍(01)
查看>>
蓝牙1.1~5.0不同版本特性简介(技术扫盲贴)
查看>>
名词王国里的死刑(翻译) - A Story of Hello World
查看>>
跟我学网站开发框架CodeIgniter之url篇
查看>>
表格响应式布局
查看>>
ssh connect no route
查看>>
iOS GCD队列dispatch简单的使用
查看>>
ARM11 paltform驱动代码完成,最简单的测试直接在装载设备中运行,实现秒读
查看>>
IDEA导入tomcat时无法导入javax.servlet.http包
查看>>
【工具使用系列】关于 MATLAB 图像处理工具箱,你需要知道的事
查看>>
对于一个程序员来说,什么最重要
查看>>
Chromium的智能指针/引用计数/Callback/Bind
查看>>