Creation and access of javascript objects

  • 2021-01-25 07:06:22
  • OfStack

JavaScript, which rarely brings to mind its object-oriented nature, is even said not to be an object-oriented language because it has no classes. Yes, JavaScript doesn't really have classes, but JavaScript is an object-oriented language. JavaScript has only objects, and objects are objects, not instances of classes.
Because objects in most object-oriented languages are class-based, there is often confusion between the concept of an instance of a class and an object. An object is an instance of a class, which is true in most languages, but not in JavaScript. Objects in JavaScript are prototype-based.

Creating and accessing

An object in JavaScript is essentially an associative array of properties consisting of names and values of any data type, functions and other objects. Note that JavaScript has functional programming features, so a function is also a variable, and most of the time is not distinguished from a 1-like data type.

In JavaScript, you can create a simple object using the following methods:


var foo = {};
foo.prop_1 = 'bar';
foo.prop_2 = false;
foo.prop_3 = function() {
return 'hello world';
}
console.log(foo.prop_3());

var foo = {}; Create 1 object and assign its reference to foo,
foo.prop1 is used to get and assign its members, where {} is the object literal, or to explicitly create an object using var foo = new Object().
1. Use an associative array to access object members
We can also use associative array mode to create the object, the above code is changed to:


var foo = {};
foo['prop1'] = 'bar';
foo['prop2'] = false;
foo['prop3'] = function() {
return 'hello world';
}

In JavaScript, the use of the period operator is equivalent to an associative array reference, that is, any object (including
ES37en pointer) can use both modes. The advantage of associative arrays is that we can use variables as indexes to associative arrays when we don't know the name of the object's properties. Such as:


var some_prop = 'prop2';
foo[some_prop] = false;

2. Create objects using object initializers
This is just to give you a sense of the definition of an JavaScript object. When it comes to actual use, we'll use the following more compact and straightforward method:


var foo = {
  'prop1': 'bar',
  prop2: 'false',
  prop3: function (){
  return 'hello world';
  }
};

This defined method is called an object initializer. Note that when using initializers, quotation marks are optional for object property names; they are not necessary unless there are Spaces or other potentially ambiguous characters in the property names.

The above is the javascript to create and access the object to achieve the method, I hope to help you learn.


Related articles: