Home  >  Article  >  Web Front-end  >  What is a literal? How to use literals to create objects in JS?

What is a literal? How to use literals to create objects in JS?

青灯夜游
青灯夜游forward
2022-08-04 18:02:093121browse

How to use literals to create objects in JavaScript? The following article will take you to understand literals and introduce how to use object literals to create objects in JavaScript. I hope it will be helpful to you!

What is a literal? How to use literals to create objects in JS?

What is a literal

Literal is a representation of a fixed value , also called a constant, is used to assign a value to a variable.

In layman’s terms, what you see is what you get. When a js program executes a literal in the code, it will immediately know what type of data it is. , what is the value?

can be used to represent fixed values, such as: numbers, strings, undefined, Boolean types, object literals, etc.

Object literal creation Object

The object literal method is one of the most commonly used ways to create objects. It uses curly braces containing attributes {...} to quickly create object.

var 对象名={ 
    .....
};

The object literal value is a list of zero or more "property name:value" of an object enclosed in a pair of curly braces ({}).

Example:

var person={ 
    name:"Jack", 
    age:10,
    5:true  
};
  • In this example, the left curly brace ({) represents the object literal Start because it appears in expression context.

  • Expression context in JavaScript refers to the ability to return a value (expression).

  • The assignment operator (=) indicates that it is followed by a value, so the left curly brace here indicates the beginning of an expression.

  • The same curly braces, if they appear in a statement context, such as following an if statement condition, indicate the beginning of a statement block.

  • The example defines the name attribute, followed by a colon, and then the value of this attribute (name:"Jack") . In object literals, use commas to separate different properties, so "Jack" is followed by a comma. But , you cannot add a comma after the of the age attribute value 10, because age is the last attribute of this object. Adding a comma after the last attribute will cause an error in IE7 and earlier and Opera.

  • Don’t forget to end the right side of the curly brace (;)

for object literals Value type

The value of an object literal can be any data type including array literals, functions, nested object literals

var Swapper = {    
        // 数组字面量(用逗号分隔,所有都要加引号)
    images: ["smile.gif", "grim.gif", "frown.gif", "bomb.gif"],
    pos: { 
            //嵌套对象字面量
        x: 40,
        y: 300
    },
    onSwap: function() { 
            //函数
    }
};
  • If there is any syntax Rules that are broken, such as missing commas or colons or braces, will trigger JavaScript errors.
  • Browser error messages are generally helpful in pointing out the location of an object literal syntax error, but they are not necessarily entirely accurate in pointing out the nature of the error.

When using object literals, the property name can also be a string

var person={
    "name":"Jack",
    "age":29,
    5:true
};
  • The above example will create an object containing three properties , but the numeric attribute names here will be automatically converted to strings.
  • When defining an object through an object literal, the Object constructor will not actually be called (the Object constructor will be called in Firefox 2 and earlier versions; but not after Firefox 3)
    This is because The literal method of creating an object emphasizes that the object is only a mutable hash map, not a property or method extracted from the object.

When the attribute name and variable name are the same, they can be abbreviated

var obj = { name: name, age: age };

// ES2015中,属性名和变量名相同时可简写为:
var obj = { name, age };

Extended attributes

// 扩展属性,ES2018新特性,可用于克隆或合并对象,浅拷贝,不包括原型
var obj2 = { ...obj3 };

Object properties created in literal mode are writable, enumerable and configurable by default

What is a literal? How to use literals to create objects in JS?

Call of object

Attribute call in object: Object.property name, this little dot. is understood as "of"

Another way to call the properties in the object: Object['property name'], note that the properties in the square brackets must be enclosed in quotation marks, we will use the method call in the object later: Object.Method name(), please note that the method name must be followed by brackets

var obj1 = {
    dogName: '可可',
    type: '阿拉斯加犬',
    age: 5 + '岁',
    color: 'red',
    skill: function () {
        console.log('技能' + ':' + 'bark' + ',' + 'showFilm');
    }
}
console.log(obj1.dogName);
obj1.skill();

Description:

The prototype of the object defaults to Object.prototype. Change the prototype by defining the value of the attribute __proto__ (only colon-marked attribute definitions can be used). The object's prototype will be set to the given value only if the given value is an object or null, otherwise the prototype will not change.

var obj1 = {};
Object.getPrototypeOf(obj1) === Object.prototype;	// true

var obj2 = { __proto__: null };
Object.getPrototypeOf(obj2) === null;				// true

var __proto__= {};
var obj3 = { "__proto__": __proto__ };
Object.getPrototypeOf(obj3) === __proto__;			// true
// 不使用冒号标记的属性定义,不会变更对象的原型,只是名字为__proto__的普通属性
var obj4 = { __proto__ };
Object.getPrototypeOf(obj4) === __proto__;			// false
obj4.hasOwnProperty("__proto__");					// true
Object.getPrototypeOf(obj4) === Object.prototype;	// true

var obj5 = { __proto__: "not an object or null" };
obj5.hasOwnProperty("__proto__");					// false
Object.getPrototypeOf(obj5) === Object.prototype;	// true

【Related recommendations: javascript learning tutorial

The above is the detailed content of What is a literal? How to use literals to create objects in JS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete