技术水平实在太差,进度缓慢。😔
最近在看的是各种源码的实现,call啊apply啊new啊等。一个简单的create的实现,我都搞了好久没弄好。记录下来,算是反馈。
Object.prototype.mycreate = function (obj,desc){ var a = {};//创建一个新对象 //ERROR —— a.prototype = obj;//**不能这么写,因为原型是隐式挂载的 a.__proto__ = obj;//制定新对象的原型为传入的对象 //传入的参数放到新对象上 // if(desc.hasOwnProperty(item)){//解决方案:!!那就添加个判断来过滤吧。 for(item in desc){//**这种方式会把原型上的"mycreate"遍历出来赋值过去,因为它是自定义的属性 a[item] = desc[item].value; } // } if(desc){ console.log(desc['mycreate']);//QUESTION——这里能打印出来 console.log('有这个属性否:'+desc.hasOwnProperty('mycreate'));//QUESTION——这里是false,说明不是自身属性 console.log("可枚举"+desc.propertyIsEnumerable('mycreate'));//QUESTION——这里也是false,说明不能被枚举(可为啥还是被显示出来了……难道因为是自定义属性就这么皮么) } return a}//以下为验证/******************************************传递对象********************************************************/var p = { name:'ggg'}//无参数传递var u = Object.mycreate(p);var y = Object.create(p);console.log(u);//{}console.log(y);//{}//有参数传递var t = Object.mycreate(p,{ age: { value: '22' }})var s = Object.create(p,{ age: { value: '22' }})console.log(t);//{age: "22", mycreate: undefined} Q:为啥这里会被附上mycreate属性?——因为这个属性是自定义的console.log(s);//{age: "22"}console.log(t[name],s[name]);//俩都是undefined,说明name是原型上的属性/***********************************************传递函数***************************************************/function o(sex){ this.sex = sex}//无参数var v = Object.mycreate(o);var z = Object.create(o);console.log(v);//Funciotn {}console.log(z);//Function {}//有参数var v = Object.mycreate(o,{ age: { value: '22' }});var z = Object.create(o,{ age: { value: '22' }});console.log(v);//Function {age: "22", mycreate: undefined}——只要有属性传参就不行console.log(z);//Function {age: "22"}实在搞不懂。为啥传入的desc里没有mycreate属性,遍历的时候却能拿到。但是用propertyIsEnumerable方法验证的时候却返回false……
只好加个验证来判断了。
话说我的注释什么时候能精简&全英文,那就比较规范了吧哈哈.
还有,我明明写的代码块里的内容,保存就变成行内了……恕我愚笨。再见。