Four ways to create objects

Four ways to create objects

  • Method 1: Express by object literal scale (also called direct quantity, original method).object literals
  • Mode two: through new and constructors Object(), String(), and so on.
  • Mode 3: Initialize a new object with a custom constructor.
  • Mode 4: through Object.create()

Mode 1: Object literals expressed by object literals (also called direct quantity, original mode)

var obj = {name:"zyx456"};

Object literals are a list of name/value pairs, with each name/value pair separated by a comma, the names and values separated by a colon, and finally enclosed in a curly bracket as a whole.

Attribute names can be numeric, such as 5.The numeric property name is automatically converted to a string.

var person = {"name" : "Nicholas","age" : 29,5 : true};

Attribute names are usually not quoted, but the following must be quoted:

  • There are spaces in the property name.
  • Has hyphen'-'
  • About keywords, such as "for".

In ES5 (and some implementations of ES3), reserved words can be used as unquoted attribute names.For ES3, however, using reserved words as attribute names must be quoted.

Example:

var person = {
    name : "Nicholas",
    age : 29};

In ES5, the comma after the last attribute in the object direct quantity can be omitted, and it can be omitted in most implementations of ES3, but errors occur in IE.

When using object literal grammar, if you leave the curly brackets blank, you can define an empty object that contains only the default attributes and methods.

var obj = {};

Object literals can also be created before adding attributes and methods.

var person = {};         //Same as new Object()
person.name = "Nicholas";
person.age = 29;

Object constructors are not actually called when an object is defined by its literal amount.

Objects can nest objects:

For example:

var myHome={
        population : "10,000" ,
        area : "10,000" ,
        adress : {  // attribute
                country : "China" ,
                province : "shanxi" ,
                city : "xian"
            },
        say : function(){  // Method
                return "My hometown is very beautiful ! ";
            }
    }

or

//Construct Nested Objects
var SchoolData = {
    code: "0123-456-789",
    Tel: "0551-1234567",
    Fax: "0551-7654321"
};
//Construct embedded objects
var ZGKJDX = {
    name: "China University of Science and Technology",
    address: "Anhui·Hefei",
    grade: "institutions of higher education",
    number: "13400",
    //Nested Object SchoolData
    data: SchoolData,
};

One drawback is that if we want to create the same object elsewhere, we have to copy and paste all the code for that object.We need a way to create the same objects in batches, not just one.

One problem is that the order of attributes cannot be guaranteed.

The order in which attributes are added may not be the order in which the output attributes are traversed.

for example

var o = {}
o.a = 1
o.b = 2
o.c = 3
for(key in o) console.log(key); // expected a,b,c - but not guaranteed to be in that order

object objects also lack a forEach method and cannot use the usual iteration method for objects.

o.forEach // undefined

Mode two: through new and constructors Object(), String(), and so on.

var obj = new Object();

The function here is called a constructor.

As follows:

var person = new Object();
person.name = "Nicholas";
person.age = 29

If the constructor has no parameters, parentheses are not required.

So you can rewrite the two lines of code as follows:

var oObject = new Object;
var oStringObject = new String;
var str  = new String();
console.log(str); // The output is String{length:0,[[PrimitiveValue]: "}
console.log(typeof str);//object;

Result:

The original JS types all contain built-in constructors.For example:

var o = new Object();           // Create an empty object, like {}
var a = new Array();            // Create an empty array as []
var d = new Date();             // Create a Date object representing the current time
var r = new RegExp("js");       //Create an EegExp object for pattern matching

In JS, such a process essentially occurs when a function is acted upon by a new operator:

First, create an empty object, then use the apply method of the function to pass in the empty object as the first parameter of the apply, as the context parameter.This is the direction of this.

var triangle = new Shape("triangle");
    //The previous sentence corresponds to the following code
var triangle = {};
Shape.apply(triangle, ["triangle"]);

Mode 3: Initialize a new object with a custom constructor.

function A(o){
this.name = "moyu"
}
let obj = new a();

Example:

function person(firstname,lastname,age,eyecolor){
    this.firstname=firstname;
    this.lastname=lastname;
    this.age=age;
    this.eyecolor=eyecolor;
}
var myFather=new person("Bill","Gates",56,"blue");
var myMother=new person("Steve","Jobs",48,"green");

How to define objects within a custom constructor:

function person(firstname,lastname,age,eyecolor)
{
    this.firstname=firstname;
    this.lastname=lastname;
    this.age=age;
    this.eyecolor=eyecolor;
 
    this.changeName=changeName;
    function changeName(name)
    {
        this.lastname=name;
    }
}

The value of the changeName() function name is assigned to the person lastname property.

myMother.changeName("Ballmer");

Mode 4: through Object.create()

Object.create() is a static function, not a method that is provided to an object instance to call.

Var O1 = Object.create ({x:1, y:2}); // O1 inherits properties X and Y

New objects can be created from any prototype (in other words, any object can be inherited).

The first parameter is the prototype of the new object.

The second parameter property descriptor object, propertiesObject, is used to further describe the properties of the object.Optional.

The properties in the property descriptor object, which are not enumerable by default, are inherited properties.

If propertiesObject is specified as undefined, it is an empty object {}.

If it is a null or non-original wrapper object, a TypeError exception is thrown.

o = Object.create(Object.prototype, {
    // foo becomes the data property of the created object
    foo: {
        writable:true,
        configurable:true,
        value: "hello"
    },
    // bar becomes an accessor property of the created object
    bar: {
        configurable: false,
        get: function() { return 10 },
        set: function(value) {
            console.log("Setting `o.bar` to", value);
        }
    }
});

Returns a new object with the specified prototype object and attributes.

Example:

var obj = Object.create({}, {p: {value: 42}});
Object.values(obj); // => []

In the code above, the object property (property p) added by the second parameter of the Object.create() method is not traversable by default unless explicitly declared, because P is an inherited property, not an attribute of the object itself.

You can create a new object without a prototype by passing in the parameter null, but the object created in this way does not inherit anything, even the underlying method, such as toString(), which means it will not work properly with the'+'operator:

var o2 = Object.create(null);      //o2 does not inherit any properties or methods

If you want to create a normal, empty object, such as one created with {} or new Object(), you need to pass in Object.prototype:

var o3 = Object.create(Object.prototype);  //o3 is the same as {} and new Object()

Example: Create a new object from prototype inheritance.

inherit() returns a new object inherited from the prototype object p.

The Object.create() function in ES5 is used here if it exists.

If Object.create() does not exist, other methods are degraded.

function inherit(p) {
        if (p == null) throw TypeError();       // p is an object, but not null
        if (Object.create)   return Object.create(p);   // If Object.create() exists, use it directly
        var t = typeof p;                       // Otherwise for further detection
        if (t !== "object" && t !== "function") throw TypeError();
        function f() {};                        // Define an empty constructor
        f.prototype = p;                        //Set its prototype property to p
        return new f();                         //Create inherited object of p using f()
}
var o = {};    
o.x = 1;      
var p = inherit(o); // p inherits o and Object.prototype
p.y = 2;        
var q = inherit(p); 
q.z = 3;      
var s = q.toString(); 
q.x + q.y       // => 3: X and y inherit from o and p, respectively

Note that inherit() does not completely replace Object.create(), it cannot create an object by passing in a null prototype, and it cannot receive an optional second parameter.

One use of the inherit() function is to prevent library functions from unintentionally (non-maliciously) modifying objects that are not under your control.

Instead of passing an object directly into the function as a parameter, pass its inherited object into the function.

When a function reads properties of an inherited object, it actually reads inherited values.

If attributes of an inherited object are assigned values, these attributes will only affect the inherited object itself, not the original object:

var o = { x: "don't change this value" };
library_function(inherit(o));   // Prevent accidental changes to o

Keywords: Javascript Attribute IE

Added by Scummy12 on Sat, 03 Aug 2019 08:13:43 +0300