search
HomeWeb Front-endJS TutorialDetailed explanation of Object in JavaScript type system_javascript skills

Previous words

In JavaScript, objects are king; almost everything in JavaScript is an object or works like an object. If you understand objects, you understand Javascript. In JavaScript, a reference type is a data structure used to organize data and functionality together. It is also often called a class. Reference types are sometimes called object definitions because they describe the properties and methods of a class of objects

Most reference type values ​​are instances of the Object type; moreover, Object is also the most commonly used type in JavaScript. Although Object instances don't have much functionality, they are really ideal for storing and transferring data in your application

Create object

There are two ways to create Object types

[1]Object constructor

var person = new Object();
//如果不给构造函数传递参数可以不加括号 var person = new Object;
person.name = 'bai';
person.age = 29; 
//创建无属性的空对象
var cody1 = new Object();
var cody2 = new Object(undefined);
var cody3 = new Object(null);
console.log(typeof cody1,typeof cody2, typeof cody3);//object object object 
//创建string、number、array、function、boolean、regex
console.log(new Object('foo'));
console.log(new Object(1));
console.log(new Object([]));
console.log(new Object(function(){}));
console.log(new Object(true));
console.log(new Object(/\bbt[a-z]+\b/));

[Note] The Object() constructor itself is an object, and the constructor is an object created based on the Function constructor

[2]Use object literals

Javascript provides shortcuts called literals for creating most native object values. Using literals just hides the same

as using the new operator

Basic process

var person = {
name : 'bai',
age : 29,
5 : true
};

[Note] Use commas in object literals to separate different properties, but adding a comma after the last property will cause an error in IE7-

Use the object literal method to define the object, and the attribute name will be automatically converted into a string

//同上
var person = {
'name' : 'bai',
'age' : 29,
'5' : true
};

If you leave its curly braces empty, you can define an object containing only default properties and methods

//等价于var person = new Object();
var person = {}; 
[tips]使用对象字面量封装多个可选参数
function displayInfo(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: 'Nicholas',
age: 29
});
displayInfo({
name: 'match'
});

The above parameter passing mode is most suitable for situations where a large number of optional parameters need to be passed to the function. Generally speaking, while named parameters are easy to handle, they can be inflexible when there are multiple optional parameters. Therefore, use formal parameters for required values, and use object literals to encapsulate multiple optional parameters

Set object

There are two ways to access object properties. You can use dot notation or bracket notation to get, set or update the properties of an object

The two advantages of the square bracket method are that attributes can be accessed through variables, and attribute names can be Javascript invalid identifiers

[Note] Chinese characters can exist in variables, because Chinese characters are equivalent to characters and are treated the same as English characters, so they can be written as person.白 or person['白']

var myObject = {
123:'zero',
class:'foo'
};
console.log(myObject['123'],myObject['class']);//'zero' 'foo'
console.log(myObject.123);//报错

If the value in square brackets is a non-string type, it will be implicitly converted to a string using String() and then output; if it is a string type, if there are quotes, the original value will be output, otherwise it will be recognized as a variable. If the variable If it is not defined, an error will be reported

person[0] = 1; //[]中的数字不会报错,而是自动转换成字符串
person[a] = 1; //[]中符合变量命名规则的元素会被当成变量,变量未被定义,而报错
person[''] = 2; //[]中的空字符串不会报错,是实际存在的且可以调用,但不会在控制台右侧的集合中显示
person[undefined 或 null 或 true 或 false] = 4;// 不会报错,而是自动转换成字符串
person['白'] = 6; // 不会报错 

Delete object

The delete operator can be used to completely delete a property from an object. Delete is the only way to delete a property from an object. Setting a property to undefined or null can only change the value of the property without deleting the property from the object. delete can only delete the data under the object, the other five basic types of values ​​cannot be deleted

[Note] delete will not delete properties found on the prototype chain

var foo = {bar: 'bar'};
delete foo.bar;
console.log('bar' in foo);//false 
var a = 123;
delete a;
console.log(a);//123

If you declare a variable a in the global state, it is equivalent to a data a under the window object. You can assign a value to a through window.a or a, and the values ​​​​of window.a and a are always equal, but they cannot be deleted.

var a;
a = 10;
console.log(a,window.a);//10 10
window.a = 20;
console.log(a,window.a);//20 20
delete a ;
console.log(a,window.a);//20 20
delete window.a;
console.log(a,window.a);//20 20

If you use window.b to declare and assign a value (b is equivalent to declaring it under the window object), you can delete it, and using delete b and delete window.b have the same effect. After deletion, console.log(b) prompts the variable Does not exist, console.log(window.b) prompts undefined

window.b = 10;
console.log(b,window.b);//10 10
delete b;
console.log(b);//报错
console.log(window.b);//undefined 
window.b = 10;
console.log(b,window.b);//10 10
delete window.b;
console.log(b);//报错
console.log(window.b);//undefined 

Object nesting

Objects can be nested, but values ​​must be obtained layer by layer

var student = {
name : {
chinese : 1,
englisth : 2
},
sex : 1,
age : 26
}

[Note] The value can only be taken layer by layer, such as student.name.chinese, and cannot cross name. Use student.chinese directly, because there may also be elements called chinese under the same level as name

var object1 = {
object1_1:{
object1_1_1:{foo: 'bar'},
object1_1_2:{}
},
object1_2:{
object1_2_1:{},
object1_2_2:{}
}
};
console.log(object1.object1_1.object1_1_1.foo);//bar

实例方法

  constructor:保存着用于创建当前对象的函数
  hasOwnProperty(propertyName):用于检查给定的属性在当前对象实例中(而不是在实例的原型中)是否存在。其中,propertyName必须以字符串形式指定

  isPrototypeOf(object):用于检查传入的对象是否是传入对象的原型

  propertyIsEnumerable(propertyName):用于检查给定的属性是否能够使用for-in语句来枚举。其中,propertyName必须以字符串形式指定

  toLocaleString():返回对象的字符串表示,该字符串与执行环境的地区对应

  toString():返回对象的字符串表示

  valueOf():返回对象的字符串、数值或布尔值表示,通常与toString()方法的返回值相同

var myObject = {
mark: true
};
console.log(myObject.constructor);//function Object(){}
console.log(myObject.hasOwnProperty('mark'));//true
console.log(Object.prototype.isPrototypeOf(myObject));//true
console.log(myObject.propertyIsEnumerable('mark'));//true
console.log(myObject.toLocaleString());//[object Object]
console.log(myObject.toString());//[object Object]
console.log(typeof myObject.valueOf(),myObject.valueOf());// object Object{mark:true}

小结:

Object类型

  对象其实就是一组数据和功能的集合。对象可以通过执行new操作符后跟要创建的对象类型的名称来创建。而创建Object类型的实例并为其添加属性和(或)方法,就可以创建自定义对象。

var o = new Object(); 

  Object的每个实例都具有下列属性和方法: 

  ● constructor——保存着用于创建当前对象的函数
   ● hasOwnProperty(propertyName)——用于检查给定的属性在当前对象实例中(而不是在实例的原型中)是否存在。其中,作为参数的属性名(propertyName)必须以字符串形式指定(例如:o.hasOwnProperty("name"))
   ● isPrototypeOf(object)——用于检查传入的对象是否是另一个对象的原型
   ● propertyIsEnumerable(propertyName)——用于检查给定的属性是否能够使用for-in语句来枚举 
  ● toString()——返回对象的字符串表示
   ● valueOf()——返回对象的字符串、数值或布尔值表示。通常与toString()方法的返回值相同。

Statement
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
JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),