The definition of an object in JavaScript is: a collection of unordered attributes, whose attributes can include basic values, objects or functions. You can think of an object as a hash table, which is a set of name-value pairs (key:value), where the value can be data or a function. Each object is created based on a reference type.
Understanding objects
In the previous blog, I wrote that there are two ways to create objects, one is to create an instance of object, and the other is to create an object instance. One is to use the object literal method:
var person = new Object(); person.sex = man; person.name = bluce person.age = 58; person.sayHi() = function(){ console.log('Hello World!'); }
but more often it is to use the following method
var person = { sex:man, name:'bluce', age:'58', sayHi:function(){ console.log('Hello World!'); } }
to create objects
A single object can be created using both the Object constructor and the object literal method, but there are obvious disadvantages: creating many objects using the same interface will produce a lot of duplicate code. Commonly used methods for creating objects include factory pattern, constructor model, and prototype pattern.
I have a question here: after adopting the AMD specification, a single js file written can be regarded as a module, or a "class". Now it is somewhat different from the concept of "class" in JavaScript. I'm confused, I hope I can clarify the application scenarios later.
The editor will introduce you to the JavaScript object-oriented programming tutorial here. I hope it will be helpful to you!
Let’s add JavaScript object-oriented design to you - factory pattern
The factory pattern is a well-known design pattern in the field of software engineering. This pattern abstracts the creation of concrete Object procedures can use functions to encapsulate the details of creating objects with specific interfaces.
I have used this design pattern in DAO in Java before and it is relatively easy to understand.
function createPerson(name,age,sex){ var obj = new Object(); obj.name = name; obj.age = age; obj.sex = sex; obj.sayHi() = function(){ console.log(this.name); }; //引号不要漏掉,养成好的习惯 return obj; } var person1 = createPerson("bluce",58,"man"); var person2 = createPerson("john",68,"man");
Use this function to create a Person object containing necessary information based on the received parameters. This function can be called an unlimited number of times, each time returning an object containing three properties and one method. The factory pattern solves the problem of creating multiple similar objects, but does not solve the problem of object recognition (how to know the type of an object).
The above is the entire content of this chapter. For more related tutorials, please visit JavaScript Video Tutorial!