zoukankan      html  css  js  c++  java
  • Object.create()和new 创建对象的区别

    Object.create()方法是ECMAScript5中新增的,用来规范化原型式继承的。
    这个方法接收两个参数,一个是用作新对象原型的对象,和一个为新对象定义额外属性的(可选)对象。

      var person = {
          name: "Nicholas",
          friends: ["John", "Jane"] // 引用类型值属性共享
        }

        var onePerson = Object.create(person); // onePerson继承person对象
        
        console.log(onePerson)  //{},自己空对象,可以通过隐士原型继承person
        console.log(onePerson.name,onePerson.friends )  //Nicholas , ["John", "Jane"]

        onePerson.name = "Greg";
        onePerson.friends.push("Mike"); 
        console.log(onePerson.name); //onePerson自己添加的name属性  Greg
        console.log(onePerson.friends); //修改person原型对象的friends ["John", "Jane", "Mike"]
        console.log(onePerson); //{name: "Greg"}
     
    // 第二个参数对象格式与Object.defineProperties()方法的第二个参数格式相同
    var theOtherPerson = Object.create(person, {
                  name : {
                    configurable : false,  // 不可修改
                    value : "Greg"
                  }
    });
    console.log(theOtherPerson.name);  // Greg
    theOtherPerson.name = "Bob";  // 失效
    console.log(theOtherPerson.name);  // Greg


    new Object()方法的实质是,使用引用类型Object的构造函数创建了一个新的实例,这个实例拥有Object默认的方法如toString、toLocaleString等。
  • 相关阅读:
    理解SetCapture、ReleaseCapture、GetCapture(控制了消息发往哪个窗口,是理解消息的关键)
    Javascript 的addEventListener()及attachEvent()区别分析
    鼠标拖拽
    鼠标右键菜单
    keydown
    一串跟随鼠标的DIV
    event对象和事件冒泡
    发表说说
    文档流
    CSS3 @keyframes 规则
  • 原文地址:https://www.cnblogs.com/fsg6/p/13245998.html
Copyright © 2011-2022 走看看