web Front-end Getting Started to Practice: Four Ways for Js to Create Objects

Keywords: Attribute Programming IE

Four Ways to Create Objects

  • The first way is through the object literal quantity representation (also known as direct quantity, original way). object literals
  • Mode 2: Through new and constructor Object(), String(), etc.
  • Mode 3: Initialize new objects with custom constructors.
  • Mode 4: Through Object.create()

Method 1: Objectliterals are expressed by object literals (also known as direct quantities and primitive ways)

var obj = {name:"zyx456"};

Object literals are a list of name/value pairs, separated by commas between each name/value pair, colons between names and values, and finally bracketed by 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. The following conditions must be quoted:

  • There are spaces in the attribute name.
  • Has a hyphen "-"
  • There are keywords, such as "for".

In ES5 (and some implementations of ES3), reserved words can be used as unquoted attribute names. However, for ES3, the use of reserved words as attribute names must be caused by quotation marks.

In the sixth year of my work, I would like to share with you some details of learning methods and practical development. 767-273-102 autumn skirt. How to learn the front-end from the zero foundation? Look at how our predecessors went ahead in the world of programming! Keep updating the latest teaching and learning methods (web front-end system learning route, detailed front-end project teaching videos), want to learn the front-end of the web, or transfer, or college students, as well as work to enhance their ability, small partners who are learning are welcome to join. We'll go with each other. Front end, front end, front end


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 also be ignored in most implementations of ES3, but in IE an error is reported.

When using object literal grammar, if you leave the curly braces blank, you can define empty objects that contain only default attributes and methods.

var obj = {};

Object literals can also be created first, followed by attributes and methods.

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

Object constructors are not actually called when objects are defined by object literals.

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 ! ";


//Constructing nested objects
var SchoolData = {
    code: "0123-456-789",
    Tel: "0551-1234567",
    Fax: "0551-7654321"
//Constructing 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: If we want to create the same object elsewhere, we have to copy and paste all the code of the object. We need a way to create the same object 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 output attributes are traversed.

for example

web Front-end development learning Q-q-u-n:  767273102 ,Share learning methods and small details that need attention, and keep updating the latest teaching and learning methods (detailed front-end project teaching video)

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 forEach methods and cannot use the usual iteration methods for objects.

o.forEach // undefined

Mode 2: Through new and constructor Object(), String(), etc.

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 necessary.

So the above two lines of code can be rewritten in the following form:

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

All JS primitive types contain built-in constructors. For example:

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

In JS, the process of acting on a function by a new operator essentially occurs:

First, an empty object is created, and then the empty object is passed in as the first parameter of the application, as the context parameter, using the application method of the function. That 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 new objects with custom constructors.

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


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

The method of defining objects within a custom constructor:

function person(firstname,lastname,age,eyecolor)

    function changeName(name)

The value of the changeName() function name is assigned to the last name attribute of person.


Mode 4: Through Object.create()

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

var o1 = Object.create({x:1, y:2}); // o1 inherits attributes x and y

New objects can be created through arbitrary prototypes (in other words, arbitrary objects 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.

Attributes in attribute descriptor objects are inherited attributes, which are not enumerated by default.

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

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

o = Object.create(Object.prototype, {
    // foo becomes the data attribute of the created object
    foo: {
        value: "hello"
    // bar becomes the 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 properties.


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 will not inherit anything, not even the underlying methods, such as toString(), which means that it will not work properly with the "+" operator:

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

If you want to create an ordinary empty object, such as one created by {} 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 through 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, further testing will be carried out.
        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 p's inheritance object 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 objects by passing in a null prototype, and it cannot accept an optional second parameter.

One of the uses of inherit() functions 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, it passes its inherited object into the function.

When a function reads attributes 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:

web Front-end development learning Q-q-u-n:  767273102 ,Share learning methods and small details that need attention, and keep updating the latest teaching and learning methods (detailed front-end project teaching video)

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

Posted by amjohnno on Tue, 10 Sep 2019 00:04:27 -0700