An overview of JavaScript objects

Source: Internet
Author: User

An overview of JavaScript objects
最简单的概述:在JavaScript中对象仅仅是属性的容器。每个对象都可以有零个或多个属性值, 这些属性持有一个基本类型的值,也可以是持有一个对象引用。
Common ways to create objects in JavaScript
JavaScript中常见的常见对象的方式有三种:    . 使用对象字面量    var obj = {}    . 使用new运算符     var obj = new Object()    . 使用create()函数  var obj = Object.create(null);这三种创建对象的方式的区别在与对象初始化的方式。具体参考后面的文章。
Adornment Object
We can decorate an object with a property descriptor.  The specific methods that can be modified are: 1.     Configurable attributes (* * configurable *) When the value of this property descriptor is: True, the property can be removed from the parent object and the descriptor of the property can be modified in the future;  When the value of this property descriptor is: False, the descriptor of the property is locked and will not be modified in the future.    e.g: "' JavaScript var person = {}; The human gender is not modifiable (we only consider the normal situation here) Object.defineproperty (person, "gender", {configurable:false, value: ' Mal    E '});    The person's name is the object.defineproperty that can be modified (man, "name", {configurable:true, Value: ' Sereno '});    Delete Person.gender;  Console.log (Person.gender);  = = Male Delete person.name console.log (person.name);  = = undefined Object.defineproperty (person, "gender", {configurable:true, Value: ' Female '}); = = uncaught Typeerror:cannot redefine property:gender person.gender = ' female '; The changes here will not be executed correctly and will throw an error Console.log (Person.log) in strict mode; The =>male ' modifier is primarily used to protect objects from being modified, a form of defensive programming that allows our own defined objects to behave in the same way as language built-in objects.   2. Enumerable attribute (* * enumerable *) When the value of this property modifier is: True, this property can be traversed. When the value of this property modifier is: False, this property is not allowed to be traversed.    e.g: "' JavaScript var person = {}; Object.defineproperty (person, "secret", {confingurable:true, enumerable:false, value: ' Just not '    Hing Tell u! '    }); Object.defineproperty (Person, "notify", {configurable:true, enumerable:true, Value: "It ' s New T    IME! "});    For (var prop in person) {Console.log (prop); }//= Notify Console.log (Object.keys (person)); = = [notify] Console.log (Object.getownpropertynames (person)); = = [' Secret ', ' Notify '] Console.log (object.propertyisenumerable (' secret ')); = = False ' Note: This property is only hidden in traversal, not completely hidden from the property and cannot be accessed, we can still use it. or [] operator to reference the property.    3. Writable Features (* * writable *) When the value of this property modifier is: True, the value associated with this property can be changed. When the value of this property modifier is: False, the value associated with this property cannot be changed.    e.g: "' JavaScript var person = {};    Object.defineproperty (person, ' gender ', {writable:false, Value: ' Male '});    Person.gender = ' female '; COnsole.log (Perosn.gender); Male ""
Checking objects
使用对象检查的方式,我们可以获取得到对象属性的修饰符的值1. Object.getOwnPropertyDescriptor    通过该方法,可以获取对象属性特性的配置。    ```JavaScript    var obj = {prop : ‘prop1‘};    Object.getOwnPropertyDescriptor(obj, ‘prop‘); // => Object {value: "prop1", writable: true, enumerable: true, configurable: true}    ```2. Object.getOwnPropertyNames    通过该方法,可以返回对象的全部属性的名字,包括enumerable属性修饰符的值为 false 的属性也能被返回。    ``` JavaScript    var obj = Object.create({}, {        innerFunc : {            enumerable : false,            value : function () {            }        },        demo : {            enumerable : true,            value : 12        }    });    console.log(Object.getOwnPropertyNames(obj)); // => ["innerFunc", "demo"]    ```3.Object.hasOwnProperty    JavaScript中,我们在遍历对象的属性时,往往只需要获取对象自身特有的属性即可,而不需要获取对象原型链上的属性。这时我们需要使用 Object.hasOwnProperty 来帮助我们甄别属性是属于原型链还是对象自身。(这里不再列举演示代码了)。4. Object.keys    返回对象中可以枚举的属性。* 更多的对象检查方法请参考 ECMAScript-262 规范中对 Object 对象的定义 *
modifying objects
前面两点主要是针对对象的结构入手,这一小节主要是针对对象整体特性来讨论。1. 冻结对象(** Object.freeze() **)    冻结对象可以有效的防止对象被再次改变。被冻结的对象不能在添加新的属性,已有的属性也不能被移除,已有属性的值也不可被更改。    ``` JavaScript    var obj = {        demo : ‘demo‘,        arr : [12, 13, 14]    }    console.log(Object.isFrozen(obj)); // => false    Object.freeze(obj);     console.log(Object.isFrozen(obj)); // => true    delete obj.demo; // 在使用 ‘ use strict‘ 声明的时候,将抛出错误    console.log(obj.demo); // => demo    obj.demo = ‘newDemo‘;    console.log(obj.demo); // => demo     obj.newProp = ‘prop‘;    console.log(obj.newProp); // => undefined    ``` 2. 密封对象(** Obejct.seal **)    密封对象比冻结对象更加严格, 具体这里不再演示和详述,因为实际使用时大部分情境采用冻结对象就足够了,如果有使用密封对象的需求,可以参见 ECMAScript 规范。* 更多的对象修改方法请参考 ECMAScript-262 规范中对 Object 对象的定义 *
Object method Borrowing
    当我们需要在一个A对象中使用别的对象的方法,而且同时想要该方法在外界看来就像是A对象自己的方法一样时,我们可以通过 ** call() ** 和 ** apply() ** 函数来实现。    这两个函数的行为非常的相似,区别在与:    call 函数接受一个参数列表, apply 函数接受一个参数数组。  这两个函数都可以有效的帮助我们使用临时函数来扩充对象的空能。具体的使用这里限于篇幅,不再进行代码演示。 关于这两个方法的详细介绍将在另一篇文章中叙述。
Creating objects
Remember: * * everything except null and undefined in JavaScript is treated as an object! * * Do you doubt the correctness of this sentence? Do you want to ask the JavaScript number 1 is also the object? I can tell you clearly: * No doubt!!! The number 1 is also an object in JavaScript. You try to use (1). toString () or 1..toString () * 1.toString () or get an error because the JavaScript interpreter interprets it. There may be decimals behind, and there is no difference between integers and floating-point numbers in JavaScript. Do you remember???    1. Create object Method--object literal ' ' ' JavaScript var obj = {Demo: ' demo ', Func:function () {}};        The object literal can visually reflect the internal structure of the object, making it easy to create a specific object quickly. Unlike: the new Object () and object.create () syntax, the literal syntax is not displayed because in a particular context, the literal is actually used as a shortcut to the Object.create () method.    Object literal syntax creates an object that does not have an explicit constructor, which also means that the literal object cannot be used as an object factory. Object literals are also a common means of implementing * single-case * design patterns. 2. New Object () it is possible to directly discuss the new operator. It's easier to understand what this syntax does: when we instantiate an object with the new operator, JavaScript actually does a 4 step: 1): JAVASCRI        PT creates a new empty object-equivalent to creating an object literal {} 2): JavaScript links the newly created empty object's constructor to the class.        3): JavaScript links the prototype of the newly created object to the prototype of the class. 4): JavaScript assigns the passed-in parameter to the newly created object. 3. Object.create () This method is introduced in ECMAScript 5, the Obejct.create () method can accept two parameters: one is the object that provides the prototype, and the other is an optional Property object that contains the configuration of the newly created object.    "' JavaScript var obj = {func:function (num) {return num;        }} var person = object.create (obj, {' demo ': {prop: ' Pro ', arr: [1, 3, 5, 7, 9]    }    }); Console.log (Person.func (test));  = = Test "* More on object creation, see" JavaScript Advanced Programming "(third edition) of the Great God Nicholasc.zakas

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

An overview of JavaScript objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.