zoukankan      html  css  js  c++  java
  • Object.create用法

    用法: Object.create(object, [,propertiesObject])

    创建一个新对象,继承object的属性,可添加propertiesObject添加属性,并对属性作出详细解释(此详细解释类似于defineProperty第二个参数的结构)

    var banana= {
        color: 'yellow',
        getColor: function(){
            return this.color
        }
    }
    //创建对象sub_banana
    var sub_banana= Object.create(banana) console.log(sub_banana.color) //yellow console.log(sub_banana.getColor()) //yellow

    添加propertiesObject

    "use strict"
    var banana= {
        color: 'yellow',
        getColor: function(){
            return this.color
        }
    }
    var sub_banana= Object.create(banana, {
      //添加taste属性 taste: {
        //详细解释 writeable:
    false, get: function(){ console.log('getTaste') return 'good' } },
      //添加weight
      weight: {
        value: 600
      } }) console.log(sub_banana.color) console.log(sub_banana.getColor()) console.log(sub_banana.taste) //good
    console.log(sub_banana.weight) //600 sub_banana.taste
    = 'bad' //报错,writeable为false不可改变

    此方法也常用于创建对象实例

    function theSuper(_a){
        this.a= 100
    }
    theSuper.prototype.getA= function(){
        return this.a
    }
    //继承prototype
    var sub1= Object.create(theSuper.prototype)
    //继承prototype而不是构造函数内的值 console.log(sub1.a) //undefined sub1.a
    = 100 console.log(sub1.getA()) //100

    那么,此方法与new obj()的区别在哪?

    Object.create的实现核心代码:

    Object.create =  function (o) {
        var F = function () {};
        F.prototype = o;
        return new F();
    };

    可见: 创建函数,将传递的对象赋给函数的prototype,再返回函数实例。

    new obj()的核心实现代码:

    var o1 = new Object();
    o1.[[Prototype]] = Base.prototype;
    Base.call(o1);

    创建对象,将被继承对象的prototype赋给此对象,并且调用被继承对象的方法来为其初始化。(因此new obj()不仅能继承prototype,也能继承构造函数内属性)

  • 相关阅读:
    spring声明式事务
    spring的传播行为和隔离级别
    索引(index)
    存储过程(转)
    Java中ArrayList相关的5道面试题
    记CVTE2014年春季招聘实习生求职历程
    Java中String,StringBuffer,StringBuilder的区别及其使用
    Linux下C程序的编译,运行,及调试
    skynet源码分析之skynet_server
    skynet源码分析之skynet_module
  • 原文地址:https://www.cnblogs.com/yanze/p/8085565.html
Copyright © 2011-2022 走看看