Dynamically create properties of objects using javascript

不言
Release: 2018-11-06 17:59:22
Original
3098 people have browsed it

Object-oriented JavaScript provides great flexibility when coding on the client side, and properties on Javascript objects help set values that can be used within the object to manage and use data.

My understanding of properties in JavaScript is that in javascript, properties can be created by defining variables on text objects.

For example

var obj = { property1: '', property2: '' };
Copy after login
Copy after login

These properties can now be accessed by using

obj.property1 = 'some value'; obj.property2 = 'some other value';
Copy after login

Also, similarly, they can also be used within functions within the object Object.

For example:

var obj = { property1: '', property2: '', foo : function(){ console.log(obj.property1); }};
Copy after login

Now that we know how to create properties on javascript objects, let’s see how to create dynamic properties on Javascript

There are two ways to do it This

Defining Array-like dynamic properties on Javascript objects

Let’s take the same example as above:

var obj = { property1: '', property2: '' };
Copy after login
Copy after login

In the object Objo To create a dynamic property on the object, we can do this:

obj['property_name'] = 'some_value';
Copy after login

What it does is that it creates a new property obj on the object and you can access it as console.log(obj.property_name);

This will output the value some_value

on the console. Use Object.defineProperty to define dynamic properties.

Example:

// Example of an object property added with defineProperty with a data property descriptor Object.defineProperty(obj, "property3", {value : 'some value', writable : true, enumerable : true, configurable : true}); // 'property3' property exists on object obj and its value is 37
Copy after login

The above is the detailed content of Dynamically create properties of objects using javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!