This is the 14th day of my participation in the August Text Challenge.More challenges in August

Create object 1

An object in ECMAScript is simply a collection of data and functionality. Objects can be created by executing the new operator followed by the name of the object type to be created. By creating an instance of type Object and adding properties and methods to it, you can create custom objects as follows:

var o = new Object(a); o.name ="Alvin"; // Add attributes
// Add method
o.sayHello = function(){
    console.log("hello "+ this.name);
}
Copy the code

This syntax is similar to the syntax for creating objects in Java, but in JavaScript you can omit the following pair of parentheses if you pass no arguments to the constructor. That is, without passing an argument, as in the previous example, it is perfectly possible to omit the parentheses (but not recommended)

var o = new Object; // Valid, but not recommended
Copy the code

Just creating an Object instance isn’t really that useful, but it’s important to understand one important idea: in JavaScript, the Object type is the basis for all other instances, and we’ve already talked about inheritance: all other types inherit from Object. That is, any properties and methods of the Object type also exist in more concrete objects.

Each instance of Object has the following properties and methods:

  • Costructor: Holds the function used to create the Object. For the above example, the constructor is Object().
  • HasOwnProperty (propertyName) : Checks whether a given property exists in the current instance object (not in the instance stereotype). Where the propertName must be specified as a string, for example, O.hasownProperty (“name”)
  • IsPropertyOf (Object) : Used to check whether an incoming object is a prototype of another object
  • PropertyIsEnumerable (propertyName) : Checks if a given property can be enumerated using a for-in statement. As with the hasOwnProperty() method, the property name as an argument must be specified as a string.
  • ToLocalString () : Returns a string representation of an object that corresponds to the locale of the execution environment.
  • ToString () : Returns a string representation of an object.
  • ValueOf () : Returns a string, numeric, or Boolean representation of an object, usually the same value as the toString() method.

Because Object is the foundation of all objects in JavaScript, all objects have these basic properties and methods.

Create Object 2

Another way to create an object is to use the representation of an object literal. An object literal is a shorthand for an object definition. The goal is to simplify the process of creating objects with a large number of attributes. Consider the following example:

var person = {
    name: "Alvin".// Add the name attribute
    // Add the sayHello method
    sayHello:function(){
        console.log("Hello "+ this.name)
    }
}
Copy the code

When using object literals, attribute names can also be strings, as shown below:

var person = {
    "name": "Alvin"."Age": 28.5: true
}
Copy the code

In this example we create a Person object with three attributes, name, age, and 5. But here the numeric attribute name is automatically converted to a string.

In addition, when using object literal syntax, if the contents inside the curly braces are empty, you can dynamically add properties or methods outside, as shown below:

var person = {}; // Same as new Object()
person.name = "Alvin";
person.sayHello = function(){
    console.log(this.name);
}
Copy the code

conclusion

While you can create objects in any of the previous ways, we usually prefer object literal syntax because it requires less code and gives the impression of encapsulating data. Object literals are actually the first way to pass a lot of optional arguments to a function. Look at the following example:

function dispalyInfo(args){
    var output = "";
    if(typeof args.name == "string"){
        output += "Name: " + args.name + "\n";
    }

    if(typeof args.age == 'number'){
        output += "Age: " + args.age + "\n";
    }

    console.log(output);
}

displayInfo({
    name: "Alvin",
    Age: 28
});

displayInfo({
    name: "yannis"
});
Copy the code

In this example, the displayInfo function takes a parameter named args, which may have an attribute named name or age, or both or neither. Inside the function, the presence of each attribute is detected through the Typeof operator, and the information is displayed based on the corresponding attribute.

In general, object properties are accessed using dot notation, which is common in many object-oriented languages. But you can also use square brackets in JavaScript to access properties like an array. When square brackets are used, the attributes to be accessed are placed in square brackets as strings. As follows:

console.log(person["name"]);
console.log(person.name);
Copy the code

Both methods are acceptable, and there is no difference in functionality between the two methods. But the main thing about square bracket access is that you can access properties in the form of variables, for example:

var proName = "name";
console.log(person[proName]); //Alvin
Copy the code

If the attribute name contains characters that cause syntax errors, or the attribute name uses keywords or reserved words, square brackets can also be used, as in:

person["first name"] = "Alvin";
Copy the code

Because “first name” contains Spaces, it cannot be accessed directly as a dot. However, attribute names can also contain non-alphanumeric and non-numeric attributes, which can be accessed using square brackets.

In general, dot notation is recommended unless you must use variables to access attributes.