search
HomeWeb Front-endJS TutorialDetailed explanation of object properties in JavaScript
Detailed explanation of object properties in JavaScriptNov 28, 2019 pm 05:37 PM
jsObject properties

Detailed explanation of object properties in JavaScript

The concept of objects in JavaScript can indeed be confusing. Look at the following example:

var strPrimitive = "I'm mamacat";
typeof strPrimitive; // "string"
strPrimitive instanceof String; // false

var strObject = new String("I'm mamacat");
typeof strObject; // "object"
strObject instanceof String; // true

strPrimitive.substr(8, 3); // "cat"

The same string is assigned to an object. Sometimes it is a string type and sometimes it is an object. However, variables that are obviously not object types can still use object attributes. Why is this?

[Related course recommendations: JavaScript video tutorial]

Types and built-in objects

There are six main types in JavaScript (Language) types, namely string, number, boolean, null, undefined and object, among which the first five basic types are not objects (typeofing null results in "object", which is the language itself BUG). Beyond this, there are many special object subtypes, such as arrays, functions, and built-in objects.

The names of some built-in objects look the same as simple basic types, such as String, Boolean, Object and so on. In terms of expression, these built-in objects are similar to the concept of "class" in other object-oriented languages. As mentioned in the previous article, they are actually just some built-in functions that can be used to construct a corresponding subtype (don't be confused) , functions are also objects, there is no contradiction here). So we can go back to the original example. strObject is a variable constructed by the built-in function/built-in object String, corresponding to the String subtype, so it is an object, and strPrimitive is just a primitive literal value.

Of course, at the bottom of the above example, we seem to have called the substr() function on strPrimitive. This is because the JavaScript engine will convert the original literal into the corresponding object when needed, and after the conversion We can naturally use attributes to access the corresponding methods.

Object properties

So, as far as the above example is concerned, the String object instance will have the substr() function available, but according to the previous article, we can know that These "functions" themselves do not belong to an object, but these functions are essentially an attribute of the corresponding object. Of course, even if we say that a certain type of object itself has various attributes, in fact these attributes mostly exist independently, but are just related together in the form of references. This is not inconsistent with what we have learned before. . These related things are called properties of the object.

Copying of Objects

Insert a quick report. Although mentioned in the previous article, it has been repeatedly emphasized above that attributes are only independent entities that are related in the form of references. Yes, we sometimes still "take it for granted" that attributes are part of the object, and one of the easiest places to get into trouble is the copying of objects. If you think about it carefully, you will know that when we copy an object, since its attributes themselves are only reference associations, the attribute references contained in the "copied" object actually point to the same location as the attribute references of the original object:

var ori = { a : 1};
var ori_copy = ori;
ori.a = 61;
ori_copy.a; // 61

Obviously this may be different from our expectations, and if we want to truly copy the object, there is no perfectly applicable solution. In many cases, the common practice is to serialize the object and then deserialize it. Get a new object to copy the object (such as using json). Object.assign() was added in ES6 to perform a shallow copy of the object. The method is to assign all enumerable properties of the object to the new object with an equal sign. However, it should be noted that the equal sign assignment does not assign the meta-information of the attribute (attribute descriptor, described later), so you should pay special attention to it if necessary.

Attribute access and array

The way to access the properties associated with the object is through the . or [] operator, obj.a and obj["a" ] The attributes accessed are essentially the same, and the only difference between these two forms of access is whether there can be strange symbols in the names of the attributes accessed. What is thrown in the [] operator is a string. In fact, the attribute name is always a string. Of course, what may be surprising about this concept is that subscript access to arrays is not an exception. Numbers are still converted into strings before they are used.

// 对象的属性访问:
var tejilang = {1 : "Teji Wolf"};
tejilang instanceof Array; // false
tejilang["1"]; // "Teji Wolf"
tejilang[1]; // "Teji Wolf"

// 这回保证它是 Array
var macat = ["codingcat"];
macat instanceof Array; // true
macat.length; // 1
macat[0]; // "codingcat"
macat["0"]; // "codingcat"
macat.length = 20;
macat; // (20) ["codingcat", empty × 19]

数组下标既然不属例外情况,那数组对象必然有其它属性控制数组本身的行为,例如上例中,macat 数组的长度就是 length 属性所体现的,通过修改它的值也就改变了对象本身对外的表现形式。当然,由于数组本身就是对象,所以我们还是可以把数组当键值对来用,只是这种做法通常是没有意义且会让人感到困惑的。JavaScript 引擎通常都根据对象的类型做了不同程度的优化,故除了代码逻辑可读性外,合理的使用也是多少可以改善性能的。

能够通过字符访问属性还是存在一些别的好处的,比如 ES6 的可计算属性名。当然 ES6 不在本文的关注范围内,所以这里就不再讨论了。

属性描述符

有时我们可能不希望某个属性被随意修改,有时候我们需要额外配置一些属性的信息,自 ES5 起,所有的属性就都具备了“属性描述符”(Property Descriptor)来控制属性本身的这些元信息。

数据描述符

来看这个例子:

var chris = {};
Object.defineProperty(chris, "IQ", {
    value: 228,
    writable: false,
    configurable: true,
    enumerable: true
});
chris.IQ = 61; // 静默失败了,如果是严格模式则会 TypeError
chris.IQ; // 228

通过 defineProperty 可以对一个对象的属性配置其对应的属性描述符(元信息),而属性描述符则包含访问描述符和数据描述符,上面的例子中,defineProperty 的第三个参数就定义了数据的若干数据描述符,其中 writable 表示可写,configurable 表示属性是否可配置(注意,修改成不可配置是单向操作),enumerable 则表示属性是否应当出现在枚举中,比如 for..in 中。

显然我们可以通过属性描述符实现对属性的保护,而同时也存在一些方便函数来做近似的事。如 Object.preventExtensions() 会保留原有属性但禁止添加新属性,Object.seal() 会密封对象,在禁止添加新属性的基础上把原有属性标记为不可配置,Object.freeze() 会冻结对象,即在密封的基础上把数据访问属性标记为不可写。

[[Get]], [[Put]] 和访问描述符

在我们访问和赋值一个对象的属性时,实际上是通过 [[Get]] 和 [[Put]] 操作进行的,例如属性访问时,[[Get]] 会先找有没有这个属性,如果没有则会遍历对象的 [[Prototype]] 链(原型链,这次不谈这个概念)来找,实在找不到则返回 undefined 。而这个行为实际是允许我们通过设置 getter (get())和 setter (set())函数来改变的,它们被称为 访问描述符。

当我们提供访问描述符时,对应的访问操作就不再受到 value writable 属性的影响了,另外需要注意的是,尽管它们也是属性描述符,但定义 getter 和 setter 并不要求一定要通过 defineProperty 设置:

var obj = {
    get a() { // 给 a 属性定义 getter
        return this._a_;
    },
    set a(val) { // a 属性的 setter
        this._a_ = val * 2;
    }
}

obj.a = 2;
obj.a; // 4

属性存在性

因为属性的值也可能是 undefined,不存在的属性直接访问得到的也是 undefined,所以直接通过简单的属性访问是无法区分是否存在的,这时我们即可通过 in 或者 hasOwnProperty() 检查属性是否存在对象中了:

var obj = {a : 2};
"a" in obj; // true
obj.hasOwnProperty("a"); // true

尽管仍没有讲到原型链的概念,这里仍然应注意,in 操作符会检查原型链中是否存在属性,而 hasOwnProperty 则不会。另外在一些情况下,有的对象会没有 hasOwnProperty 这个属性(此处不提原因),这时可以用过 Object.prototype.hasOwnProperty.call(objName, propertyName) 来实现检查。

本文来自 js教程 栏目,欢迎学习!  

The above is the detailed content of Detailed explanation of object properties in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
如何使用JS和百度地图实现地图平移功能如何使用JS和百度地图实现地图平移功能Nov 21, 2023 am 10:00 AM

如何使用JS和百度地图实现地图平移功能百度地图是一款广泛使用的地图服务平台,在Web开发中经常用于展示地理信息、定位等功能。本文将介绍如何使用JS和百度地图API实现地图平移功能,并提供具体的代码示例。一、准备工作使用百度地图API前,首先需要在百度地图开放平台(http://lbsyun.baidu.com/)上申请一个开发者账号,并创建一个应用。创建完成

PHP Notice: Trying to get property ‘的解决方法’ of non-object的解决方法PHP Notice: Trying to get property ‘的解决方法’ of non-object的解决方法Jun 22, 2023 am 11:51 AM

当我们在使用PHP进行开发时,有时会遇到”Tryingtogetproperty‘的解决方法’ofnon-object”的错误提示。这个错误的原因一般是因为程序中对一个不存在或者未实例化的对象进行访问,导致了PHP解析器无法识别该对象的属性或方法。那么,如何解决这个错误呢?下面我将为大家介绍几种可能的解决方法。一、检查代码首先,我们需要将出错的代

js字符串转数组js字符串转数组Aug 03, 2023 pm 01:34 PM

js字符串转数组的方法:1、使用“split()”方法,可以根据指定的分隔符将字符串分割成数组元素;2、使用“Array.from()”方法,可以将可迭代对象或类数组对象转换成真正的数组;3、使用for循环遍历,将每个字符依次添加到数组中;4、使用“Array.split()”方法,通过调用“Array.prototype.forEach()”将一个字符串拆分成数组的快捷方式。

如何使用JS和百度地图实现地图热力图功能如何使用JS和百度地图实现地图热力图功能Nov 21, 2023 am 09:33 AM

如何使用JS和百度地图实现地图热力图功能简介:随着互联网和移动设备的迅速发展,地图成为了一种普遍的应用场景。而热力图作为一种可视化的展示方式,能够帮助我们更直观地了解数据的分布情况。本文将介绍如何使用JS和百度地图API来实现地图热力图的功能,并提供具体的代码示例。准备工作:在开始之前,你需要准备以下事项:一个百度开发者账号,并创建一个应用,获取到相应的AP

js中new操作符做了哪些事情js中new操作符做了哪些事情Nov 13, 2023 pm 04:05 PM

js中new操作符做了:1、创建一个空对象,这个新对象将成为函数的实例;2、将新对象的原型链接到构造函数的原型对象,这样新对象就可以访问构造函数原型对象中定义的属性和方法;3、将构造函数的作用域赋给新对象,这样新对象就可以通过this关键字来引用构造函数中的属性和方法;4、执行构造函数中的代码,构造函数中的代码将用于初始化新对象的属性和方法;5、如果构造函数中没有返回等等。

用JavaScript模拟实现打字小游戏!用JavaScript模拟实现打字小游戏!Aug 07, 2022 am 10:34 AM

这篇文章主要为大家详细介绍了js实现打字小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

php可以读js内部的数组吗php可以读js内部的数组吗Jul 12, 2023 pm 03:41 PM

php在特定情况下可以读js内部的数组。其方法是:1、在JavaScript中,创建一个包含需要传递给PHP的数组的变量;2、使用Ajax技术将该数组发送给PHP脚本。可以使用原生的JavaScript代码或者使用基于Ajax的JavaScript库如jQuery等;3、在PHP脚本中,接收传递过来的数组数据,并进行相应的处理即可。

js是什么编程语言?js是什么编程语言?May 05, 2019 am 10:22 AM

js全称JavaScript,是一种具有函数优先的轻量级,直译式、解释型或即时编译型的高级编程语言,是一种属于网络的高级脚本语言;JavaScript基于原型编程、多范式的动态脚本语言,并且支持面向对象、命令式和声明式,如函数式编程。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment