热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

jsnew、object.create、bind的模拟实现【转载备忘】

创建Person构造函数,参数为name,agefunctionPerson(name,age){this.namename;this.ageage;}funct

//创建Person构造函数,参数为name,age
function Person(name,age){this.name = name;this.age = age;
}
function _new(){//1.拿到传入的参数中的第一个参数,即构造函数名Funcvar Func = [].shift.call(arguments);//2.创建一个空对象obj,并让其继承Func.prototypevar obj = Object.create(Func.prototype);//3.执行构造函数,并将this指向创建的空对象obj
Func.apply(obj,arguments)//4.返回创建的对象objreturn obj
}xm
= _new(Person,'xiaoming',18);console.log(xm);

来源https://blog.csdn.net/u010342862/article/details/80016695

 

if (typeof Object.create !== "function") {Object.create = function (proto, propertiesObject) {if (typeof proto !== 'object' && typeof proto !== 'function') {throw new TypeError('Object prototype may only be an Object: ' + proto);} else if (proto === null) {throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument.");}if (typeof propertiesObject != 'undefined') throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument.");function F() {}F.prototype = proto;return new F();};
}

来源https://developer.mozilla.org/zh-CN/docs/Web/Javascript/Reference/Global_Objects/Object/create#Polyfill

 

if (!Function.prototype.bind) {Function.prototype.bind = function(oThis) {if (typeof this !== 'function') {// closest thing possible to the ECMAScript 5// internal IsCallable functionthrow new TypeError('Function.prototype.bind - what is trying to be bound is not callable');}var aArgs = Array.prototype.slice.call(arguments, 1),fToBind = this,fNOP = function() {},fBound = function() {// this instanceof fNOP === true时,说明返回的fBound被当做new的构造函数调用return fToBind.apply(this instanceof fNOP? this: oThis,// 获取调用时(fBound)的传参.bind 返回的函数入参往往是这么传递的
aArgs.concat(Array.prototype.slice.call(arguments)));};// 维护原型关系if (this.prototype) {// Function.prototype doesn't have a prototype propertyfNOP.prototype = this.prototype; }// 下行的代码使fBound.prototype是fNOP的实例,因此// 返回的fBound若作为new的构造函数,new生成的新对象作为this传入fBound,新对象的__proto__就是fNOP的实例fBound.prototype = new fNOP();return fBound;};
}

来源https://developer.mozilla.org/zh-CN/docs/Web/Javascript/Reference/Global_Objects/Function/bind



推荐阅读
author-avatar
阿加芬散阿加芬散
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有