object.create

串门回来难得的休息一会,我们来看看object的方法:

Object.create这个方法会使用指定的原型对象及其属性去创建一个新的对象。

用法:

Object.create(proto[, propertiesObject])

返回值是:在指定原型对象上添加新属性后的对象。(如果proto的参数不是null或者一个对象,那么他就会抛出一个TypeError)

function Parent(){}
    Parent.prototype.hello=function () {
        console.log("我是来自父类的");
    }
    function Child(){
        Parent.call(this);
    }
    //子类继承父类;
    Child.prototype=Object.create(Parent.prototype);
    Child.prototype.constructor=Child;
    var test=new Child();
    console.log(test instanceof Child);
    console.log(test instanceof Parent);
    console.log(test.hello())

上面的例子中我们定义了一个Parent函数,又定义了一个以他为原型的child函数。上面的结果是true true ,“我是来自父类的”。里面的子类继承父类用到了本文的object.create;

同样的我们还可以创建一个原型为空的对象:

  var o=Object.create(null);

下面我们用Object.create来创建一个有属性的对象,因为这个方法的第二属性是可没有的,所以说上述的例子中没有用到。

    o=Object.create(Object.prototype,{
        // foo会成为所创建对象的数据属性
        foo: {
            writable:true,
            configurable:true,
            value: "hello"
        },
        // bar会成为所创建对象的访问器属性
        bar: {
            configurable: false,
            get: function() { return 10 },
            set: function(value) {
                console.log("Setting:", value);
            }
        }
    })
这个方法的用处也就可想而知了,最后还有一个例子:
function Constructor(){}
o = new Constructor();
// 上面的一句就相当于:
o = Object.create(Constructor.prototype);
// 当然,如果在Constructor函数中有一些初始化代码,Object.create不能执行那些代码




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值