Objects in javascript are different from general object-oriented programming languages (c++, Java, etc.), and few people even say that it is an object-oriented programming language because it has no classes. JavaScript has only objects, not instances of classes. Objects in javascript are prototype-based.
1.1 Period operator creation
An object in javascript is actually an associative array composed of attributes. The attribute is composed of names and values. The type of value can be any data type, or functions and other objects.
Create a simple object:
var foo = {};foo.prop_1 = 'bar';foo.prop_2 = false;foo.prop_3 = function() {return 'hello world'; }console.log(foo.prop_3());Assign value to foo by reference, {} is a representation of the object literal value. var foo={} can also create an object display by var foo = new Object().
1.2 Create an object using an associative array.
var foo = {};foo['prop_1'] = 'bar';foo['prop_2'] = false;foo['prop_3'] = function() {return 'hello world'; }The use of period operators and associative array references in javascript are equivalent. The advantage of using associative arrays is that when we don't know the attribute name of the object, we can use variables as the index of the associative array. For example:
var some_prop = 'prop_2';foo[some_prop] = false;
1.3 Create an object using an object initializer
Generally, when we use it, we use the following method to create objects:
var foo = {prop1:'bar',prop2:false,prop3:function(){return 'hello world';}};This method of definition is called an object derived initializer
1.4 Create an object through a constructor.
The objects created earlier are all one-time. If we want to create multiple planned objects, there are several fixed properties, methods and can be initialized. We can create complex objects through constructors:
function User(name,uri){this.name = name;this.uri = uri;this.display = function() {console.log(this.name);}}Then you can create an object with a new statement.
var someuser = new User('byvoid','http://www.byvoid.com');Then you can access the properties and methods of this object through someuser.
The above is the different methods of creating objects in JavaScript introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!