• 首页 Home
  • 简介 About
  • 项目 Service
  • 案例 Cases
  • 新闻 News
  • 技术文章 本硕新闻 行业资讯

    [javascript]create创建新对象和prototype原型对象创建的区别

    发表时间:2019-02-25  热度:

    Object.create()方法创建一个新对象

    const person = {

      isHuman: false,

      printIntroduction: function () {

        console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);

      }

    };

    const me = Object.create(person);

    //var me = Object.create(person);

    me.name = "Matthew"; // "name" is a property set on "me", but not on "person"

    me.isHuman = true; // inherited properties can be overwritten

    me.printIntroduction();

    // expected output: "My name is Matthew. Am I human? true"

     

    prototype

    function person(){};

    person.prototype.text= {

      isHuman: false,

      printIntroduction: function () {

        console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);

      }

    };

    const me = new person();

    me.name = "Matthew"; // "name" is a property set on "me", but not on "person"

    me.isHuman = true; // inherited properties can be overwritten

     

    me.text.printIntroduction();

    // expected output: "My name is undefined. Am I human? false"

     
    文章怎么样?
    相关资讯