————————————————————————————————————
Object: JavaScript is a prototype-based language and does not have Class, so it will Functions as classes
The data contained in the object can be accessed in two ways
Both properties of the object (property) And method (method)
Attributes are variables belonging to a specific object, and methods are functions that can only be dispatched by a specific object.
An object is a data entity that is composed of some related properties and methods. In JavaScript, properties and methods are accessed using "dot" syntax.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Object-oriented terminology
#Object: an unordered collection of attributes, each attribute stores a primitive value, object and function
Class: Every object is defined by a class. A class not only defines the object's interface (the properties and methods that developers access), but also defines the object's inner workings (the code that makes the properties and methods work)
#Instance: When a program uses a class to create an object, the generated object is called an instance of the class. Each instance behaves the same, but the instance handles an independent set of data.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Four basic abilities
-
Encapsulation: the ability to store relevant information (regardless of data or methods) in objects
Aggregation: The ability to store one object within another object
Inherited: from another class ( or multiple classes) to derive the properties and methods of a class
Polymorphism: the ability to write functions or methods that can be run in multiple ways
—————————————————————————————— ——————————
Built-in objects
- Data Encapsulated object
- Methods that support regular objects
search
match
replace
split
Properties: Object.prototype.constructor:Returns a pointer to the prototype of the object that was created Function reference
- method:
Object.prototype.isPrototypeOf():Detect whether an object exists on the prototype chain of another object
Object.prototype.propertyIsEnumerable():Detect whether the specified property name is an enumerable self-property of the current object
Object.prototype.toString():Returns a string representing the object
Object.prototype.valueOf( ):The returned poemthis value is the object itself
ObjectObject is the parent object of all objects in Js, and all objects we create inherit from this
- method:
Object.create():指定原型对象和属性创建一个对象
Object.defineProperty():给对象添加/修改一个属性并指定该属性的配置
Object.defineProperties():在一个对象上添加或修改一个或者多个自有属性,并返回该对象
Object.keys():方法会返回一个由给定对象的所有可枚举自身属性的属性名组成的数组,数组中属性名的排列顺序和使用for-in循环遍历该对象时返回的顺序一致(两者的主要区别是for-in还会遍历除一个对象从其原型链上继承到得可枚举的属性)
Object.getOwnPropertyNames():返回一个由指定对象的所有自身属性的属性名(包括不可枚举属性)组成的数组
Object.getOwnPropertyDescriptor():返回指定对象上一个自有属性对应的属性描述符。(自有属性指的是直接赋予该对象的属性,不需要从原型链上进行查找的属性))
Object.getPrototypeOf():返回指定对象的原型(也就是该对象内部属性[[Prototype]]的值)
Object.freeze():冻结一个对象。冻结对象是指那些不能添加新的属性,不能修改已有属性的值,不能删除已有属性,以及不能修改已有属性的可枚举性、可配置性、可写性的对象。也就是说这个对象永远不能改变的
Object.isFrozen():判断对象是否已经被冻结
Object.preventExtensions():阻止对象扩展
Object.isExtensible():检测一个对象是否可扩展(是否可以在它上面添加新的属性)
Object.seal():可以让一个对象密封,并返回被密封之后的对象。密封对象是指那些不能添加新的属性、不能删除已有属性,以及不能修改已有属性的可枚举性、可配置性、可写性,但可能可以修改已有属性的值的对象
Object.isSealed():检测一个对象是否被密封sealed
- Object对象
- Object.prototype
Number对象
Boolean对象
Array对象
Function对象
- String对象
1 var myArr = new Array; 2 var str = 'this is a test hello ishello maizi'; 3 var patt = /is/ig; 4 var i = 0; 5 while ((myArr[i] = patt.exec(str)) !== null) 6 { 7 console.log(i + 1 + ':' + myArr[i] + " " + patt.lastIndex); 8 i++; 9 }10 11 str = 'this is a testis';12 patt = /is/ig;13 var res = str.match(patt);14 console.log(res);15 16 res = str.search(patt);17 console.log(res);18 19 res = str.replace(patt, '!');20 console.log(res);21 22 // 将年月日替换为月日年23 str = '2017-06-04';24 res = str.replace(/(\d{4})-(\d{2})-(\d{2})/, '$2-$3-$1');25 console.log(res);26 27 // 调用方法,将匹配到的内容替换成为hugh+匹配内容大写28 str = 'this is a testis';29 res = str.replace(/is/g, func);30 31 function func(match)32 {33 return 'hugh' + match.toLocaleUpperCase();34 }35 console.log(res);36 37 // split38 // 将匹配到的字符串前后拆分39 res = str.split(/\s+/);40 console.log(res);
- 工具类对象
Math对象
-
Date对象
1 // 显示当前时间 2 console.log(Date()); 3 // 显示毫秒数 4 var d = new Date(138555555550); 5 console.log(d); 6 // 显示填入的时间 7 var d = new Date(2011, 1, 3); 8 console.log(d); 9 // 传入月日10 var d = new Date(10,25);11 console.log(d);12 // Date提供的方法13 console.log(Date.now()); // 自1970年至今所经过的毫秒数14 console.log(Date.parse("2017-01-01")); // 解析一个字符串,返回所经过的毫秒数15 // ...
-
RegExp对象
1 // 通过test()方法检索字符串中的内容,返回true或false 2 var patt1 = new RegExp("r"); 3 var res1 = patt1.test('this is javascript course'); 4 console.log(res1); 5 // 另一种形式 6 // 加上i表示忽略大小写 7 patt2 = /Javascript/i; 8 res2 = patt2.test('this is javascript course'); 9 console.log(res2);10 // 是否包含[]中的字符11 res3 = /[abc]/.test('Brlue');12 // 加上^表示除了abc之外的13 res4 = /[^abc]/.test('Brlue');14 // 检测是否包含数字15 res5= /[0-9]/.test('999');16 // 检测是否包含字母17 res5= /[a-z]/.test('999');18 // 是否出现了以下几个19 res5= /php|javascript|ios/.test('php');20 console.log(res3);21 console.log(res4);22 console.log(res5);
- 错误对象
通常使用try/catch/finally来捕获Error错误
- Error类型
EvalError
InternalError
RangeError
ReferenceError
SyntaxError
TypeError
URIError
-
Error对象
1 try 2 { 3 // 当调用不存在的notExists(),e.name和e.message存放的错误名称和错误信息 4 // notExists(); 5 var n = 0; 6 if (n == 0) 7 { 8 // 手动抛出一个错误信息 9 throw new Error('Throw an error message');10 }11 }12 catch (e)13 {14 console.log(e.name);15 console.log(e.message);16 }17 finally18 {19 // finally中的总是被调用20 console.log('i am in finally');21 }22 23 try24 {25 notExists();26 }27 catch (e)28 {29 // 判断错误的实例化类型30 if (e instanceof EvalError)31 console.log('this is a EvalError');32 else if (e instanceof SyntaxError)33 console.log('this is a SyntaxError');34 else if (e instanceof ReferenceError)35 console.log('this is a ReferenceError');36 else37 console.log('An unknown errorr');38 }39 // 对Error对象重写40 function myError(msg)41 {42 this.name = "myError'sname";43 this.message = msg || "myError'info";44 }45 // 通过Object.create()创建错误原型46 myError.prototype = Object.create(Error.prototype);47 myError.prototype.constructor = myError;48 try49 {50 throw new myError();51 }52 catch (e)53 {54 console.log(e.name);55 console.log(e.message);56 }
自定义对象
通过var obj = {} 对象字面量法
通过var obj = new Object()创建
-
通过函数构造创建对象
p.s. 使用的时候通过new操作符得到对象
用构造器创建对象的时候可以接收参数
构造器函数的首字母最好大写,区别其他的一般函数
当我们创建对象的时候,实际上同时也赋予了该对象一种特殊的属性,即构造器属性
这个构造器属性实际上是一个指向用于创建该对象的构造器函数的引用
function Person(){}
var Persion = function(){}
- 构造器属性(constructor property)
通过instanceof操作符可以检测一个对象是否由某个指定的函数构造器创建
通过Object.create()创建对象
1 /*********************************** 2 * 对象字面量 3 ***********************************/ 4 var oTest = {}; 5 document.write(typeof oTest + ""); 6 var oTest2 = { x: 1, 'y': 2, "z": 3 }; 7 document.write(oTest2.x + " " + oTest2.y + " " + oTest2.z + ""); 8 var oTest3 = { 9 username: 'rog91222',10 passwd: '123123',11 person: {12 firstname: "hugh",13 lastname: "dong"14 },15 age: 2016 }17 document.write(oTest3.username + " " + oTest3.person.firstname + " " + oTest3.age + "");18 /***********************************19 * new Object()创建对象20 ***********************************/21 var oTest4 = new Object();22 /***********************************23 * 通过构造器函数的形式创建对象24 ***********************************/25 function funcTest(num1, num2) {26 this.n1 = num1;27 this.n2 = num2;28 }29 var oTest5 = new funcTest(1, 2);30 document.write(oTest5.n1 + " " + oTest5.n2 + "");31 // 通过instanceof检测是否由函数构造器构造的32 document.write(oTest5 instanceof funcTest);33 document.write("<br>")34 /***********************************35 * 通过Object.create()创建对象36 ***********************************/37 var oTest6 = Object.create({ x: 1 });38 // 不继承任何方法39 var oTest7 = Object.create(null);40 // 创建一个普通的空对象41 var oTest8 = Object.create(Object.prototype);
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
对象特性
- 原型(prototype)
通过对象字面量的形式创建,则使用object.prototype作为它们的原型。
通过new和构造函数创建,则使用构造函数的prototype作为它们的原型。
-
如果通过Object.create()创建,使用第一个参数(或null)作为它们的原型
var obj = Object.create({ x: 1 });
类(class)
扩展标记(extensible flag)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
对象的结构
声明对象obj,对象有2个属性 x=1,y=2,每个属性都有对应的属性特性,对象也有3个对象特性
-
对象的原型链:
如图所示,当在对象中找不到属性z时,会向方法的原型查找,继续向对象的原型查找,直到顶层null位置。
每个对象都和另外一个对象关联,就构成了一个原型链,每一个对象都从原型继承属性。
>
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
检测对象上是否有某个属性
in(包括原型上的)
- hasOwnProperty(仅检测对象自己有的属性)
1 function foo() {} 2 foo.prototype.z = 5; 3 var obj1 = new foo(); 4 obj1.x = 1; 5 obj1.y = 2; 6 console.log('x' in obj1); 7 console.log('y' in obj1); 8 console.log('toString' in obj1); 9 console.log('nonono' in obj1);10 console.log(obj1.hasOwnProperty('x'));11 console.log(obj1.hasOwnProperty('z'));
————————————————————————————————————————————
属性
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
数据属性:每个属性有4个描述行为的特性:
[writable]:是否能修改属性的值
[enumerable]:是否通过for in 循环返回属性(是否可以被枚举)
[configurable]:是否能通过delete删除,能否修改属性的特性,能否修改访问器属性
[value]:包含这个属性的数据值,读取属性值的时候从这个位置读取。默认值为undefined
存取器属性
get:获取属性的值
set:设置属性的值
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
属性操作
p.s. 正常属性名可以放在""''或不放引号内,但如果包含特殊字符、保留字、数字开头,必须放在引号之间
访问属性
添加属性
修改属性
删除属性
遍历属性
1 var person = 2 { 3 fName : 'hugh', 4 lName : 'dong', 5 age : 20 6 }; 7 // 通过.或[]来实现查询属性 8 console.log(person.fName); 9 console.log(person['lName']);10 console.log(person["age"]);11 // 如果属性不确定,需要使用[]来读取属性,此处key不能加引号12 var key = 'fName';13 console.log(person[key]);14 // 在对象内部通过this获取属性15 function PersonInfo(fName, lName, age)16 {17 this.firstName = fName;18 this.lastName = lName;19 this.year = age;20 }21 var person1 = new PersonInfo('wang', 'er', 30);22 console.log(person1.firstName);23 console.log(person1.lastName);24 console.log(person1.year);25 // 添加属性26 var obj = {};27 obj.userName = 'username';28 obj.passwd = '123456';29 obj['permissions'] = 'admin';30 console.log(obj.userName);31 console.log(obj.passwd);32 console.log(obj.permissions);33 // 修改属性34 obj.passwd = '123.com';35 console.log(obj.passwd);36 // 删除属性,删除后再打印该属性为undefined37 // p.s.delete只能删除自身的属性,不能删除集成的属性38 // 要删除继承属性,只能从定义它的属性的原型对象上删除它,会影响到所以继承这个原型的对象39 // delete只是断开属性和宿主对象的联系,而不会去操作属性的属性40 delete obj.permissions;41 console.log(obj.permissions);42 // 遍历属性43 // i存放的是属性名称,obj[i]存放的是属性值44 for (var i in obj)45 {46 console.log(i + ":" + obj[i]);47 }48 // 对象中有方法49 var obj1 =50 {51 user : '111',52 pass : '222',53 sayHi : function (x)54 {55 return this.user + x + 1;56 }57 }58 console.log(obj1.sayHi(3));
The above is the detailed content of JavaScript Basics--Objects and Properties. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software