Preface: say, dot come in like my smile!! Hello everyone, my name is C Le, a retired college student who likes motorcycle travel. After a CSS contact in class, I like the front end. The following are some of my study notes. Standing on the shoulders of the seniors, I share some of my understanding. Gender male (hahahahahaha, can’t hit me)
What are JavaScript objects?
Ecma-262 defines an object as “an unordered collection of attributes that may contain primitive values, objects, or functions”. Each property or method of an object has a name, and each name can map to a value, a name-value pair. Feeling inside, what is this (10,000 words omitted)
The first time I saw that, it was all in a fog. In fact, we can think of the object as a car. With a basic concept that a car key (function or object) matches a car (base value), it’s not that hard to move on to understanding data properties and accessor properties. The data attribute is like gasoline, and the accessor attribute is like the engine (rest assured, the car will never leak oil within 10,000 kilometers of starting, so you will never lose money if you buy it. Ok, to get to the point). After adding gasoline to the car (data type), the engine (accessor attribute has a function to determine how to process data) starts working. Then you can accompany your significant other to romantic Turkey, I heard that the front end will be handsome and well-paid little brothers and sisters, the front end to learn from the big men.
When you have a partner, you can have a person to accompany you to go shopping, eat food you want to eat for a long time, go to the movies and so on.
When you have an object, you can act in pettish and complain about grievances. Even if the matter has been solved, you can still get comfort from the other side. You can be weak, you don’t have to be brave to do everything.
When there is a partner, even if two people stay at home is also very happy, can do a lot of things, no matter what do have another person to share, sometimes will get the other side love praise.
When there is an object, when it is raining outside, you can ask the object to pick you up and give yourself an umbrella. Or you can call your partner when you are out.
That’s why it’s so important to have a date. Let me learn how to create objects in JavaScript.
In view of the length is a bit long, interested partners can collect after slowly look, passing handsome men and beautiful women god please give a small praise, writing is not easy, small to you play a set of enemy boxing to help you.
Eight ways to create objects
Object Constructor Pattern (Mercedes-benz) Object Literal pattern (BMW) Factory Pattern (Audi) Constructor pattern (Land Rover) Prototype Pattern (Volkswagen) Constructor pattern and Prototype combination (Bugatti Veyron) Dynamic Prototype Pattern (Rolls-Royce) Parasitic Constructor pattern (McLaren)
- You may ask why I add the car brand, because every time I learn a way to create objects, I feel like I own the car, ha ha ha, forgive me for fantasizing.
Object constructor pattern
var person = new Object();
person.name = "Jhonha";
person.age = '27';
person.job = 'dancer';
person1.sayName = function() { console.log(this.name); } person1.sayName(); // Jhonha console.log(person1.age); / / 27Copy the code
The constructor returns a new object instance by default if it does not return a value. By adding a return statement to the end of the constructor, you can override the return value when the constructor is called.
Object literal schema
var person = {
name: 'Jhonha',
age: 22,
job: 'dancer',
sayName: function () {
console.log(this.name);
}
}
person2.sayName(); // dancer
Copy the code
Although both Object constructors and Object literals can be used to create a single Object, these methods have the obvious disadvantage of creating many objects in one interface, resulting in a lot of repetitive code
The factory pattern
function createPerson(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function () {
console.log(this.name);
};
return o;
}
var person1 = createPerson('Jhonha', 22, 'dancer');
var person2 = createPerson('Ciris', 22, 'Software engineer'); console.log(person1.name); // Jhonha console.log(person2.name); // Ciris benefits: it solves the problem of creating multiple similar objects, the function encapsulates the creation of objects, no need to write code to create objects repeatedly. Disadvantages: it does not solve the problem of object recognition (how to know an object type), let's continue to learn.Copy the code
Constructor pattern
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function () {
console.log(this.name);
}
}
var person1 = createPerson('Jhonha', 22, 'dancer');
var person2 = createPerson('Ciris', 22, 'Software engineer');
console.log(person1.name); // Jhonha
console.log(person2.name); // Ciris
Copy the code
In this example, the Person() function replaces the createPerson () function. In addition to the same parts of the code in Person () as in createPerson (), we notice the following differences
* No obvious object is created * attributes and methods are assigned directly to this object * NonereturnstatementsCopy the code
To create a new instance of Person, you must go through four steps using the new operator
* Creates a new object * assigns the constructor's scope to the new object (so this refers to the new object) * executes the constructor's code (adds attributes to the new object) * returns the new objectCopy the code
At the end of the previous example, person1 and person2 each hold a different instance of Person. Both objects have a constructor property that points to Person.
console.log(person1.constructor === Person); // true
console.log(person2.constructor === Person); // true
Copy the code
All objects we create in this example are instances of Both Object and Person, which is verified by the instanceof operator.
console.log(person1 instanceof Object); // true
console.log(person1 instanceof Person); // true
console.log(person2 instanceof Object); // true
console.log(person2 instanceof Person); // true
Copy the code
The only difference between constructors and other functions is how they are called. However, constructors are functions, and there is no special syntax for defining constructors. Any function called with the new operator can be used as a constructor.
Var person = new person ("Jhonha", 27, "dancer");
person.sayName(); //"Jhonha"// Call Person as a normal function ("Ciris", 22, "software engineer"); // Add to window window.sayname (); //"Ciris"// Call var o = new Object() in another Object's scope; Person.call(o,"Kristen", 25, "Nurse");
o.sayName(); //"Kristen"
Copy the code
Constructor pattern optimization
function Person(name) {
this.name = name;
this.sayName = sayName;
}
function sayName() {
console.log(this.name);
}
var person1 = new Person('Jhonha'); console.log(person1.name); // Jhonha var person2 = new Person('Ciris'); console.log(person2.name); // CirisCopy the code
Advantage: Solves the problem that every method has to be recreated
Disadvantages: Person1 and person2 objects share the same sayName() function in the global scope, but functions defined in the global scope can only be called by an object. This gives the global scope a false advantage. If you want objects to define many methods, you need to define many global functions. So our custom reference type has no encapsulation at all. Fortunately, these problems can be solved by using the prototype pattern.
Thank you for seeing here. If you look long enough, you can rest
The prototype pattern
function Person(){}
Person.prototype = {
constructor : Person,
name: "Jhonha",
age : 29 ,
job: "Software Engineer",
sayName: function() {returnthis.name; }}; var person1 = new Person(); console.log(person1.name); // Jhonha console.log(person1.age); // 29 console.log(person1.job); // Software Engineer console.log(person1.sayName()); // JhonhaCopy the code
Advantages: Each function we create has a Prototype property, which is a pointer to an object whose purpose is to contain properties and methods that can be shared by all instances of a particular type. If taken literally, prototype is the prototype object of the instance of the object created by calling the constructor. The advantage of using a prototype object is that all object instances can share the properties and methods it contains.
Disadvantages: omitted initialization parameters for the constructor, all instances will get the same value by default, when using stereotype properties only changes on one instance will affect all instances, such as array changes on one instance.
I have attached a diagram to help you understand constructors, prototypes, and examples.
Picture the author
Use a combination of constructor and stereotype patterns
The most common way to create custom types is by combining the constructor pattern with the stereotype pattern. The constructor pattern is used to define instance properties, while the stereotype pattern is used to define method and shared properties. As a result, each instance has its own copy of instance attributes, but also shares references to methods, maximizing memory savings
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Jhonha"."Nick"]
}
Person.prototype = {
constructor: Person,
sayName: function () {
console.log(this.name);
}
}
var person1 = new Person('bob', 22, 'frontend');
var person2 = new Person('lynn', 22, 'doctor');
person1.friends.push("Van");
console.log(person1.friends); // Jhonha Nick Van
console.log(person2.friends); // Jhonha Nick
console.log(person1.name); // bob
console.log(person2.name); // lynn
console.log(person1.sayName === person2.sayName); // true
Copy the code
In this case, the instance properties are defined in the constructor, while the constructor property and method sayName(), shared by all instances, are defined in the stereotype. Changing person1.friends(adding a new string to it) does not affect person2.friends, since they come from different arrays.
This hybrid pattern of constructors and stereotypes is currently the most widely used and recognized method of creating defined types in ECMAScript.
Thank you for being here, thank you for having you, give me a thumbs up, thank you
Dynamic prototype pattern
function Person(name, age, obj) {
this.name = name;
this.age = age;
this.obj = obj;
console.log('typeof this.sayName: ', typeof this.sayName); The sayName method is actually only added to the prototype when it was not created the first timeif(typeof this.sayName ! ='function') {
Person.prototype.sayName = function () {
returnthis.name; }}} // Because the constructor is executed, the code inside the constructor is executed once, and the prototype does not need to be repeated every time, so only the first execution of the prototype, the subsequent execution does not need to be generated, so it is not executedif// If you want to create a new object, you can create a new object. // If you want to create a new object, you can create a new object. var person1 = new Person('bob', 22, 'frontend');
var person2 = new Person('lynn', 22, 'doctor');
console.log(person1.name); // bob
console.log(person2.name); // lynn
console.log(person1.sayName()); // bob
console.log(person2.sayName()); // lynn
console.log(person1.sayName === person2.sayName); // true
Copy the code
What is the use of if in dynamic prototyping? What are the problems or drawbacks with not using the if statement?
1. The first question :Person is a constructor, and a new Person(… To generate instance objects. The code inside Person is called every time a Person object is generated. If, every time you create a new (i.e. every time an instance object is produced), you redefine a new function and attach it to the Person.prototype.sayName property. In fact, you only need to define this property once, because all instances will share it. Therefore, if if is removed, it will cause unnecessary waste of time and space; With an if, the sayName method is defined only on the first instance of new, and not thereafter.
2. Second question: Suppose you define many other methods besides :sayName, such as :sayBye, cry, smile, and so on. All you need to do is put them in the if block for sayName.
if(typeof this.sayName ! ="function") {
Person.prototype.sayName = function() {... }; Person.prototype.sayBye =function() {... }; Person.prototype.cry =function() {... }; . }Copy the code
In this way, either they are not all defined (when the first instance is new) or they are all defined (after the other instances are new), that is, their existence is consistent and the same judgment is sufficient without the need to judge them separately.
Wow, you’re still there. Buy a cute one
Parasitic constructor pattern
The parasitic constructor pattern, based on the idea of creating a function that merely wraps the code that created the object and then returns the newly created object.
function createPerson(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function () {
console.log(this.name);
};
return o;
}
var person1 = new createPerson('bob', 22, 'frontend');
var person2 = new createPerson('lynn', 22, 'doctor');
console.log(person1.name); // bob
console.log(person2.name); // lynn
console.log(person1 instanceof createPerson ) // false
console.log(person2 instanceof createPerson ) // false
Copy the code
Parasitic constructor pattern, which I personally think should read like this:
Parasitic-constructor-pattern, that is, a way of parasitizing a constructor.
You can’t even create an instance that points to a constructor using instanceof.
Secure constructor pattern
functionPerson(name,age,job){// Create the Object to return var o = new Object(); // Private variables and functions can be defined here // add methodfunction(){ console.log(name); }; // Return the objectreturn o;
}
var friend = Person("Nicholas", 29,"dancer");
friend.sayName(); //Nicholas
Copy the code
A secure object is an object that has no public attributes and whose methods do not reference this.
There are two differences from the parasitic constructor pattern:
* The newly created instance method does not reference this * does not call the constructor using the new operatorCopy the code
Secure objects work best in secure environments. The secure constructor pattern, like the factory pattern, does not recognize the type of an object.
You are almost finished reading, one of your favorite pictures is given to you to give a thumbs-up, thank you
Small complement
What happened to the new operator?
- It creates a new object
- It will be linked by executing [[Prototype]] (that is, __proto__).
- It makes this point to the newly created object
- Each object created by new will eventually be linked to the function’s Prototype object by [[Prototype]].
- If the function does not return the Object type Object(including Functoin, Array, Date, RegExg, Error), the function call in the new expression will return the Object reference.
How do you understand instantiation
Instantiation means much the same thing. You treat a class as an object, like a car, and you want to… So you ask the compiler (in the narrow sense of the computer),var person = new person (); ‘Person’ and ‘Contructor’ are the difference in name. For example, if your dad likes to say ‘honey’ to his car, you can call it ‘baby’ when you’re driving, no matter whose car it is. The Person() cannot be changed because you have to tell the machine which car you are borrowing… Then you borrow over after whatever you call…. The method below the class ah, public attributes can be borrowed, like saying that this car has four wheels a steering wheel is the attribute, the method is that this car can be open, can also be open…. So whether you want to drive forward or backwards, you need to borrow the car in order to drive… Instantiation is borrowing a car… Call method is to borrow the car after the operation!