


Introduction to internal attributes and delete operator in js_javascript skills
Before explaining Configurable
, let’s first look at an interview question:
a = 1; console.log( window.a ); // 1 console.log( delete window.a ); // true console.log( window.a ); // undefined var b = 2; console.log( window.b ); // 2 console.log( delete window.b ); // false console.log( window.b ); // 2
From the above question, we can see two differences: when a variable is not declared using var, it can be deleted using the delete keyword, and the value will be undefined when obtained again; when a variable is declared using var, It cannot be deleted using delete, and the value is still 2 when retrieved.
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 will return false; if delete can successfully delete variable b, it will return 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 delete produces such a result. Here we only look at its return value:
Delete an element in the delete array:
// 使用for~in是循环不到的,直接忽略到该元素 // 使用for()可以得到该元素,但是值是undefined var 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 function type variables:
// 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 ); // 2 console.log( delete func1.length ); // true,删除成功 console.log( func1.length ); // 0
Delete commonly used variables:
console.log( delete NaN ); // false,删除失败 console.log( delete undefined );// false console.log( delete Infinity ); // false console.log( delete null ); // true,删除成功
Delete the prototype instead of deleting the attributes on the prototype:
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 ); // 4 console.log( delete arr.length ); // false,删除失败 console.log( arr.length ); // 4 var str = 'abcdefg'; console.log( str.length ); // 7 console.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 ); // wenzi console.log( delete obj.name ); // true,删除成功 console.log( obj.name ); // undefined console.log( obj ); // { age:25 }
When deleting attributes in an instance object, you can see from the following 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 it again, it will still be deleted. It cannot be deleted; if you want to delete the attributes or methods of the attributes on the prototype, you can only delete them: delete Person.prototype.name
:
function Person(){ this.name = 'wenzi'; } Person.prototype.name = '蚊子'; var student = new Person(); console.log( student.name ); // wenzi console.log( delete student.name ); // true,删除成功 console.log( student.name ); // 蚊子 console.log( delete student.name ); // true console.log( student.name ); // 蚊子 console.log( delete Person.prototype.name );// true,删除成功 console.log( student.name ); // undefined
2. Internal properties of js
In the above example, some variables or attributes can be deleted successfully, while others 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 (used in JS engines, not directly accessible from the outside). There are two kinds of properties in ECMAScript: data properties and accessor properties.
2.1 Data attributes
A data attribute refers to a location containing a data value at which 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. 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 anyway at this location
To modify the default characteristics of object properties (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); // wenzi console.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's properties; it is worth noting that once configurable is set to false, defineProperty can no longer be used 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 attribute, the getter will be called to return a valid value; when the accessor attribute is written, the setter will be called to write the new value; this attribute has the following 4 characteristics :
- [[Configurable]]: Whether the attribute can be deleted and redefined through the delete operator;
- [[Numberable]]: Whether this attribute can be found through a for-in loop;
- [[Get]]: Automatically called when reading properties, default: undefined;
- [[Set]]: Automatically called when writing attributes, default: undefined;
Accessor properties cannot be defined directly and must be defined using defineProperty(), 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, accessor properties (set and get) and data properties (writable or value) cannot be declared 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.
If defined as follows, accessor properties and data properties exist at the same time:
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 ); // wenzi console.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操作删除变量时产生的结果是一样的。
3. 总结
别看一个简简单单的delete操作,里面其实包含了很多的原理!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

There are two keyboard delete keys: del (delete) key and backspace key. Backspace is also called the backspace key. This key can delete the text content in front of the cursor; and the delete key can delete characters, files and selected objects. Each time you press the del key, a character to the right of the cursor will be deleted, and the character to the right of the cursor will move one frame to the left; when one or more files/folders are selected, press the Del key to quickly delete; in some applications Select an object in the program and press the Del key to quickly delete the selected object.

The functions of the delete key are: 1. Delete characters; each time the delete key is pressed, a character to the right of the cursor will be deleted, and the character to the right of the cursor will move one frame to the left. 2. Delete files; when one or more files/folders are selected, press the Delete key to quickly delete them (move to the Recycle Bin for recovery). 3. Delete the selected object; select an object in some applications and press the Delete key to quickly delete the selected object.

Control+Alt+Delete: "Mac" mode Ctrlaltdel is a common key combination used by Windows users to open Task Manager. They usually exit unwanted applications from the manager menu to free up some space on their computer. The Control+Alt+Delete Mac variant lets you open the Force Quit menu. If Mac users want to quit the program causing the problem or view open programs, they can interact with the menu to investigate further. How to perform ControlAltDelete on Mac? If you have any malfunctioning applications, you must use this key combination to

PUT and Delete requests are used in the Form form and only support get and post methods. In order to implement the put method, we can implement it through the following three steps: 1) Configure HiddenHttpMethodFilter in SpringMVC 2) Create a post form on the page 3) Create an input item, name ="_method", the value is the specified request method. Get the value of "_method" in the HiddenHttpMethodFilter class to get the new request method. The th tag is the thymeleaf template, which means that only when employee

Files deleted by delete can be recovered; because when users use delete to delete files, these files will be moved to the recycle bin and are not completely deleted. Recovery method: 1. Open the "Recycle Bin", select the file you want to restore, and click "Restore this item"; 2. Open the "Recycle Bin", select the file you want to restore, and use the undo shortcut "ctrl+z". Can.

In today's era of web development, effective and efficient table management has become very important, especially when dealing with data-heavy web applications. The ability to dynamically add, edit, and delete rows from a table can significantly enhance the user experience and make applications more interactive. An effective way to achieve this is to leverage the power of jQuery. jQuery provides many features to help developers perform operations. Table rows A table row is a collection of interrelated data, represented by elements in HTML. It is used to group together cells (represented by elements) in a table. Each element is used to define a row in the table, and for multi-attribute tables, it usually contains one or more elements. Syntax$(selector).append(co

Usage of most Linux commands using the '!' symbol may vary in different shells. While the examples I provide are typically used in bash shells, some other Linux shells may have different implementations or may not support certain uses of the '!' symbol at all. Let’s dive into the surprising and mysterious uses of the ‘!’ symbol in Linux commands. 1. Use the command number to run a command from the history. What you may not know is that you can run a command from the command history (commands that have already been executed). First, find the number of the command by running the 'history' command. linuxmi@linuxmi:~/www.linuxmi.

Database Delete usage: 1. Delete a single record; 2. Delete multiple records; 3. Delete all records; 4. Delete records with specific conditions.
