Home > Web Front-end > JS Tutorial > body text

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

青灯夜游
Release: 2022-08-04 18:03:52
forward
3123 people have browsed it

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 对象名={ 
    .....
};
Copy after login

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  
};
Copy after login
  • 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() { 
            //函数
    }
};
Copy after login
  • 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
};
Copy after login
  • 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 };
Copy after login

Extended attributes

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

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();
Copy after login

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
Copy after login

【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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template