


Detailed explanation of delete operator and internal attribute instances in js
This article mainly shares with you the detailed explanation of delete operator and internal attribute examples in js. Before explaining Configurable, let’s first look at an interview question:
a = 1;console.log( window.a ); // 1console.log( delete window.a ); // trueconsole.log( window.a ); // undefinedvar b = 2;console.log( window.b ); // 2console.log( delete window.b ); // falseconsole.log( window.b ); // 2
From the above question, we can see two The difference: when a variable is not declared using var, it can be deleted using the delete keyword, and the value when obtained again will be undefined; when a variable declared using var is deleted, it cannot be deleted using delete, and the value when obtained again is still 2. .
1. delete operator
When you use delete to delete a variable or attribute, it returns true if the deletion is successful, otherwise it returns false. As in the above example, if delete cannot delete variable a, it returns false; if delete can successfully delete variable b, it returns true.
In addition to the above two situations, there are various other commonly used variables that can be deleted by delete, and some that cannot be deleted. Let’s not worry about why such a result occurs when deleting these variables. Here we only look at its return value:
Delete one element in the delete array:
// 使用for~in是循环不到的,直接忽略到该元素 // 使用for()可以得到该元素,但是值是undefinedvar arr = [1, 2, 3, 4];console.log( arr ); // [1, 2, 3, 4]console.log( delete arr[2] ); // true,删除成功console.log( arr ); // [1, 2, undefined, 4]
Delete a variable of function type :
// chrome 不能删除;火狐可以删除function func(){ } console.log( func );console.log( delete func ); console.log( func );
Delete function.length, which is the number of formal parameters obtained:
function func1(a, b){ }console.log( func1.length ); // 2console.log( delete func1.length ); // true,删除成功console.log( func1.length ); // 0
Delete common variables:
console.log( delete NaN ); // false,删除失败console.log( delete undefined ); // falseconsole.log( delete Infinity ); // falseconsole.log( delete null ); // true,删除成功
Delete the prototype, rather than deleting the prototype. Attributes:
function Person(){ } Person.prototype.name = "蚊子";console.log( delete Person.prototype ); // false,无法删除console.log( delete Object.prototype ); // false
When deleting the length of arrays and strings:
var arr = [1, 2, 3, 4];console.log( arr.length ); // 4console.log( delete arr.length ); // false,删除失败console.log( arr.length ); // 4var str = 'abcdefg';console.log( str.length ); // 7console.log( delete str.length ); // false,删除失败console.log( str.length ); // 7
When deleting attributes in obj:
var obj = {name:'wenzi', age:25};console.log( obj.name ); // wenziconsole.log( delete obj.name ); // true,删除成功console.log( obj.name ); // undefinedconsole.log( obj ); // { age:25 }
When deleting attributes in instance objects, from the following It can be seen from the output that when you use delete to delete attributes, only the attributes of the instance object itself are deleted, and the attributes on the prototype cannot be deleted. Even if you delete them again, they cannot be deleted; if you want to delete the attributes of the attributes on the prototype or The method can only be: delete Person.prototype.name:
function Person(){ this.name = 'wenzi'; } Person.prototype.name = '蚊子';var student = new Person();console.log( student.name ); // wenziconsole.log( delete student.name ); // true,删除成功console.log( student.name ); // 蚊子console.log( delete student.name ); // trueconsole.log( student.name ); // 蚊子console.log( delete Person.prototype.name ); // true,删除成功console.log( student.name ); // undefined
2. js internal attributes
In the above example, some variables or attributes can be deleted successfully, while others Variables or attributes cannot be deleted, so what determines whether this variable or attribute can be deleted.
ECMA-262 5th Edition defines the characteristics of JS object properties (for JS engines, not directly accessible from the outside). There are two kinds of properties in ECMAScript: data properties and accessor properties.
2.1 Data attribute
A data attribute refers to a location containing a data value where the value can be read or written. This attribute has 4 properties that describe its behavior:
. [[configurable]]: Indicates whether it can be deleted and redefined using the delete operator, or whether it can be modified as an accessor attribute. The default is true;
. [[Enumberable]]: Indicates whether the attribute can be returned through a for-in loop. Default true;
. [[Writable]]: Indicates whether the value of the attribute can be modified. Default true;
. [[Value]]: Contains the data value of this attribute. This value is read/written. The default is undefined; for example, the name attribute is defined in the instance object Person above, and its value is 'wenzi'. Modifications to this value are done at this location.
To modify the default characteristics of the object attributes (the default is true) ), you can call the Object.defineProperty() method, which receives three parameters: the object where the property is located, the property name and a descriptor object (must be: configurable, enumberable, writable and value, one or more values can be set).
is as follows:
var person = {};Object.defineProperty(person, 'name', { configurable: false, // 不可删除,且不能修改为访问器属性 writable: false, // 不可修改 value: 'wenzi' // name的值为wenzi});console.log( person.name); // wenziconsole.log( delete person.name ); // false,无法删除person.name = 'lily';console.log( person.name ); // wenzi
It can be seen that neither delete nor reset the value of person.name takes effect. This is because calling the defineProperty function modifies the characteristics of the object properties; it is worth noting that once If configurable is set to false, you can no longer use defineProperty to modify it to true (execution will report an error: Uncaught TypeError: Cannot redefine property: name);
2.2 Accessor properties
It mainly includes A pair of getter and setter functions. When reading the accessor property, the getter will be called to return a valid value; when the accessor property is written, the setter will be called to write the new value; this property has the following 4 characteristics:
. [[Configurable]]: Whether the attribute can be deleted and redefined through the delete operator;
. [[Numberable]]: Whether the attribute can be found through a for-in loop;
. [[Get]]: Automatically called when reading properties, default: undefined;
. [[Set]]: Automatically called when writing properties, default: undefined;
Accessor properties cannot be defined directly and must use defineProperty() To define, as follows:
var person = { _age: 18};Object.defineProperty(person, 'isAdult', { Configurable : false, get: function () { if (this._age >= 18) { return true; } else { return false; } } });console.log( person.isAdult ); // true
However, there is still one thing that needs extra attention. When setting properties with the Object.defineProperty() method, you cannot declare accessor properties (set and get) and data properties (writable or value) at the same time. . This means that if a property has a writable or value attribute set, then this property cannot declare get or set, and vice versa.
如若像下面的方式进行定义,访问器属性和数据属性同时存在:
var o = {};Object.defineProperty(o, 'name', { value: 'wenzi', set: function(name) { myName = name; }, get: function() { return myName; } });
上面的代码看起来貌似是没有什么问题,但是真正执行时会报错,报错如下:
Uncaught TypeError: Invalid property. A property cannot both have accessors and be writable or have a value
对于数据属性,可以取得:configurable,enumberable,writable和value;
对于访问器属性,可以取得:configurable,enumberable,get和set。
由此我们可知:一个变量或属性是否可以被删除,是由其内部属性Configurable进行控制的,若Configurable为true,则该变量或属性可以被删除,否则不能被删除。
可是我们应该怎么获取这个Configurable值呢,总不能用delete试试能不能删除吧。有办法滴!!
2.3 获取内部属性
ES5为我们提供了Object.getOwnPropertyDescriptor(object, property)来获取内部属性。
如:
var person = {name:'wenzi'};var desp = Object.getOwnPropertyDescriptor(person, 'name'); // person中的name属性console.log( desp ); // {value: "wenzi", writable: true, enumerable: true, configurable: true}
通过Object.getOwnPropertyDescriptor(object, property)我们能够获取到4个内部属性,configurable控制着变量或属性是否可被删除。这个例子中,person.name的configurable是true,则说明是可以被删除的:
console.log( person.name ); // wenziconsole.log( delete person.name ); // true,删除成功console.log( person.name ); // undefined
我们再回到最开始的那个面试题:
a = 1;var desp = Object.getOwnPropertyDescriptor(window, 'a');console.log( desp.configurable ); // true,可以删除var b = 2;var desp = Object.getOwnPropertyDescriptor(window, 'b');console.log( desp.configurable ); // false,不能删除
跟我们使用delete操作删除变量时产生的结果是一样的。
相关推荐:
JavaScript delete操作符应用实例_javascript技巧
The above is the detailed content of Detailed explanation of delete operator and internal attribute instances in js. 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

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.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools