Results 1 to 1 of 1

Thread: The best way to instantiate a new object

  1. #1
    Join Date
    Jan 2017
    Posts
    24
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Question The best way to instantiate a new object

    Hey,

    There are 3 different ways to create a new object:
    Code:
    let myObject = {};
    Code:
    var myObject = {
        name: “Engage",
        days: 30
    }
    Code:
    var myObject = new Object();
    Now my question is about the 2 different ways of instantiating a new object.

    You can either use an existing object as prototype of your new object, like this:

    Code:
    var person = {
      name: "David",
      age: 20,
    };
    
    // Create theDude object and use person object as its prototype
    var theDude = Object.create(person);
    Or you can use a Constructor function to create your new object like this:

    Code:
    function Person (name) {
        this.name = name;
        this.age = 20;
        this.getInfo = function getInfo() {
            return this.name + ' is ' + this.age + ' years old.';
        };
    }
     
    // Instantiating a new object using the new keyword and a constructor function
    var theDude = new Person("David");

    My question is:

    What is the difference between the last 2 methods of instantiating a new object?
    Which method is more recommended?
    In the real world, which one is used more?

    Thanks
    Last edited by kayut; 05-28-2018 at 04:29 PM.

Similar Threads

  1. create moving object from a set of data points
    By BienvenueJS in forum JavaScript
    Replies: 7
    Last Post: 11-24-2015, 07:07 PM
  2. Replies: 2
    Last Post: 12-12-2012, 09:54 AM
  3. object doesn't support this object in javascript
    By ryoka012 in forum JavaScript
    Replies: 1
    Last Post: 06-24-2011, 01:23 PM
  4. Replies: 3
    Last Post: 03-13-2009, 08:24 AM
  5. Create object; load file in the object
    By molendijk in forum JavaScript
    Replies: 0
    Last Post: 03-09-2008, 07:30 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •