Basic concepts
1, Custom objects.
According to the object extension mechanism of JS, users can customize JS objects, which is similar to the Java language.
Corresponding to custom objects are JS standard objects, such as Date, Array, Math, etc.
2, prototype (prototype)
In JS, this is a way to create object properties and methods. New properties and methods can be added to objects through prototype.
Through prototype we can add new properties and methods to JS standard objects. For example, for String objects, we can add a new method trim().
Unlike strict programming languages (such as Java), we can dynamically add new properties to JS objects during runtime.
Object creation method
1) Object initializer method
Format: objectName = {property1:value1, property2:value2,…, propertyN: valueN}
property is the attribute of the object
value is the value of the object. The value can be one of three strings, numbers or objects
For example: var user= {name: "user1",age:18};
var user={name:"user1",job:{salary:3000,title:programmer}
In this way also Methods that can initialize objects, for example:
var user={name:“user1”,age:18,getName:function(){ return this.name; } }
The following will focus on the constructor method, including the definition of attributes and methods, etc., and also explain the constructor method.
2) Constructor method
Write a constructor and create the object through new method. The constructor can have construction parameters
For example:
function User(name,age){ this.name=name; this.age=age; this.canFly=false; } var use=new User();
The above is the detailed content of Detailed explanation of the basic concepts and creation methods of JavaScript custom objects. For more information, please follow other related articles on the PHP Chinese website!