Home >Web Front-end >JS Tutorial >Introduction to objects in JavaScript_javascript skills

Introduction to objects in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:23:131089browse

In JavaScript, except number, string, boolean, null and undefined, all other values ​​are objects. Objects can be declared directly through literals or created through the new operator. Unlike the Java language, properties in JavaScript objects can be dynamically added or deleted; at the same time, properties in objects can also be empty strings:


Copy code The code is as follows:

//properties in object can be added/deleted dynamically
var o = {x:1, y:2};
console.log(o);//Object {x=1, y=2}
delete o.y;
o.z = 3;
console.log(o);//Object {x=1, z=3}

//empty string is allowed as object property
var o2 = {"":88, "p":99};
console.log(o2);//Object { =88, p=99}

//for constructor function, "new" operation returns an object.
function Computer(x, y) {
this.x = x;
this.y = y;
}
var c = new Computer(126, 163);
console.log(c);//Computer {x=126, y=163}
var c2 = new Computer(126);//missing parameter value will be "undefined"
console.log(c2);//Computer {x=126, y=undefined}
c.z = 66;
console.log(c);//Computer {x=126, y=163, z=66}
delete c.y;
console.log(c);//Computer {x=126, z=66}

If the function used when using the new operator to create a new object is not a class constructor, but just an ordinary function, then JavaScript will return an empty object after executing the function:

Copy code The code is as follows:

//for pure function, "new" operation returns an empty object.
function compute(x){
console.log("execute function compute");
Return x*2;
}
var a = new compute();
console.log(a);//compute {}

Object property

Object in JavaScript has the following 3 properties:

1.prototype. Reference, pointing to the prototype object of Object. Properties in prototype objects can be inherited by Object.
2.class. A string representing the class name of Object.
3.extensible. A boolean value indicating whether dynamic addition of properties is allowed in the Object. This property is only valid in ECMAScript 5.

Property attribute

Property in Object also has 3 attributes:

1.writable. Whether the property is writable.
2.enumerable. Whether the property will be enumerated when using the for/in statement.
3. configurable. Whether the properties of this property can be modified and whether the property can be deleted.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn