An analog implementation Object.create, custom prototype property to traverse it

Recently read is to achieve a variety of source, call new ah ah ah apply and so on. Create a simple implementation, I have for a long time did not do things right. Recorded, considered feedback.


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"}

Really do not understand. Why there are no incoming desc mycreate property, traversing the time able to get. But with propertyIsEnumerable way to verify when they return false ......

We had to add validation to judge.

When the words of my comments can streamline & in English, it is fairly standard it ha ha.

Released three original articles · won praise 0 · Views 31

Guess you like

Origin blog.csdn.net/suisui0725/article/details/104503039