Javascript basics-create an object

Source: Internet
Author: User

Today, I went back to school from home, stayed at home for ten days, gained a few pounds of weight, and went back to school. It was a hard journey to go home during the Spring Festival. To save money, I have no choice but to transfer direct flights to or from Changchun to Beijing. In this way, my girlfriend and I can save about 4000 yuan. January 24 Shenzhen-plane-Beijing (the plane was delayed for one hour). It was already more than two o'clock in Beijing, and there were only two airport buses left, when I got a bus to the city, I got my 100 yuan out of my classmates. When I got to my classmates (near tiantongyuan), I had three o'clock. I had to eat and drink (a bottle of niulanshan + 2 bottles of beer) at five o'clock, after sleeping at, I got up and played basketball for two hours. When I came back, I didn't have dinner. I went to the station. I almost didn't catch up with the train to go to Changchun. at, I arrived in Changchun, take a taxi to the Changchun Tech students and have a KFC take-out in the evening. There are no more than 100 items. Go to bed at one o'clock P.M. and get up and drive back to Songyuan to the countryside to attend the wedding. at, I will come back as a car to go home. Ah, it's time to die. My uncle and uncle take turns to eat at home every day and play mahjong every day ...... get up at half past four on January 1, February 6 get up and take a bus to the city for a train to go to Changchun to catch up with the bus to Beijing. At around, we arrived in Beijing and took the money to the Capital Airport to fly directly to Hong Kong, to Hong Kong at a.m., take the bus back to Shenzhen Bay and go to the dormitory at a.m. I feel like I 've been driving cars all the time. If I have money, I just need to fly directly. Now, let's talk about how to learn about objects in javascript and how to create objects. What is an Object in Object javascript? Everything in javascript is an Object, and all objects are Object-based. Specifically, every Object is created based on a reference type, this reference type can be native or created by ourselves. These reference types are Object-based. The simplest way to create an Object is var person = new Object (); person. name = "hainan"; person. age = "25"; create an Object directly, and then add attributes and methods to the Object. In the fifth version of javascript, attribute types define features used internally and describe various features of attributes. These features are used by the javascript engine and cannot be used in javascript, in order to distinguish them, they are placed in two brackets. The attribute types are divided into two types: data attributes and accessors attributes. The data attribute [[retriable] indicates whether the attribute can be deleted through delete. The default value is true [[Enumerable], which indicates whether the attribute can be enumerated through for-in, the default Value is true [[Writable], which indicates whether the attribute Value can be modified. The default Value is true [[Value], which indicates the attribute Value, the default value is the undefined accessors attribute [[retriable], which indicates whether the attribute can be deleted through delete. The default value is true [[Enumerable], which indicates whether the attribute can be enumerated through for-in, the default value is true [[Get]. The read attribute is the called function. The default value is the function called when undefined [[[Set] is written to the attribute. The default value is undefinedECMAScript5, and the Object is used when the attribute is modified. the defineProperty () method has three parameters: object, attribute name, And descriptor object. Let's look at the example. The value feature var person ={}; Object. defineProperty (person, "name", {retriable: true, value: "hainan"}) console. log (person. name); // hainan // equivalent to var person = {name: "hainan"} and then look at writable var person = {}; Object. defineProperty (person, "name", {retriable: true, value: "hainan", writable: false}); person. name = "allenxing"; // modify the properties console. log (person. name); // if an error occurs in hainan strict mode, see the configuration feature var person ={}; Object.. DefineProperty (person, "name", {retriable: false, value: "hainan"}); delete person. name; // Delete the property console. log (person. name); // in strict hainan mode, the configuration attribute is changed to not configurable, that is, when it is set to false, it cannot be changed to configurable, take a look at the example var person ={}; Object. defineProperty (person, "name", {retriable: false, value: "hainan"}); Object. defineProperty (person, "name", {retriable: true, value: "hainan"}); // TypeError: Cannot redefine property: nameenume Rable copy code var person ={}; Object. defineProperty (person, "name", {retriable: true, value: "hainan"}); for (var pro in person) {console. log (pro) ;}// no output // In chrome, the default enumeration is false by default. Copy the code var person ={}; Object. defineProperty (person, "name", {retriable: true, value: "hainan", enumerable: true}); for (var key in person) {console. log (key)} // "name" Let's take a look at the accessors property copy code var person = {name: "hainan", age: 25} Object.de FineProperty (person, "year", {get: function () {return this. age + 1 ;}, set: function (value) {this. age = value + 10 ;}}); console. log (person. year); // 26person. year = 10; console. log (person. age); // 20 copy the code ECMAScript5. There is also a method Object. defineProperties () can define multiple attributes. The usage is as follows: copy the code var person = {} Object. defineProperties (person, {name: {value: "hainan"}, age: {value: 25}, year: {get: function () {return this. age + 1; }, Set: function (value) {this. age = value + 10 ;}}); console. log (person. year); // 26person. year = 10; console. log (person. age); // 25 note that the copy code here does not know why the value of age has not changed, but the copy code var person = {name can be changed as follows: "hainan", age: 25} Object. defineProperties (person, {year: {get: function () {return this. age + 1 ;}, set: function (value) {this. age = value + 10 ;}}); console. log (person. year); // 26person. year = 10; console. Log (person. age); // 20 pay attention to copying the code here. Thank you for your guidance. In fact, the above attributes cannot be used in general, understanding this helps us better understand javascript objects. There are many ways to create an Object directly by creating a new Object. The simplest method is to directly create an Object, and then add the property var person = new Object (); person. name = "hainan"; person. age = 25; object literal volume is a commonly used method for object creation. In fact, it is similar to new, but it is relatively simple to write var person = {name: "hainan ", age: 25} disadvantages: It looks simple, but if we want to create multiple objects, such as person1, person2 ....., code must be rewritten for both new and object literal, that is, there will be a lot of repeated code. Factory mode: The factory mode solves the problem that the Code cannot be reused. The factory mode encapsulates the process of creating an object using a function. Check the code to copy the code function personFactory (name, age) {var obj = new Object (); obj. name = name; obj. age = age; return obj;} var person1 = personFactory ("hainan", 25); var person2 = personFactory ("allenxing", 26 ); copy the code so that you only need to use personFactory () to create a person object. This solves the complicated code problem of creating multiple objects. In fact, we can see that the essence is to directly create an Object, but it is encapsulated with a function, and return this Object with a return. Disadvantage: we do not know which type of instance this Object belongs to, that is, it does not solve the problem of Object recognition. Of course, it does not make any substantive sense to know that the Object is an Object instance. Constructor mode constructor can create specific types of objects. Objects and arrays are native constructor and exist in the execution environment when javascript is running, we do not need to define constructors by ourselves. When we need to customize objects, we can customize constructors and copy the code function Person (name, age) {this. name = name; this. age = age;} var person1 = new Person ("hainan", 25); var person2 = new Person ("allenxing", 26 ); copy the code. here we can see that the first letter of the function is capitalized. This is a convention to be different from other functions. To create an instance of Person, you must use the new operator to see what new has done. Create a new object and assign the scope of the constructor to this object, that is, this points to the Code in executing the constructor of this new object and returns that the new object person1 and person2 are different instances of the Person object. They have the same constructor attribute, and they are all Person instance consoles. log (person1.constructor = Person); // trueconsole. log (person2.constructor = Person); // trueconsole. log (person1 instanceof Person); // trueconsole. log (person2 instanceof Person); // The true constructor mode solves the problem of object recognition. We know that constructor is also a function. If the new keyword is not used, what will happen? In global scope, this points to window, then you can directly use the constructor to add the property or method to the window. Let's see if this is the case and copy the code function Person (name, age) {this. name = name; this. age = age;} var person = Person ("hainan", 25); // added to the console on the window. log (window. name); // when the hainan copy Code does not have a new instance, the constructor is a normal function and added to the object to which this points. Here this points to window. Disadvantage: every time a new instance comes out, every instance has to re-create the object function. The function in each instance is different, because the function is also an object, defining a function is to instantiate an object. Copy the code function Person (name, age) {this. name = name; this. age = age; this. getName = function () {return this. name}; // equal to this. getName = new Function ("return this. name ");} var person1 = new Person (" hainan ", 25); var person2 = new Person (" allenxing ", 26); console. log (person1.getName = person2.getName); // false copy the code. Although this function is shared by the instance, each instance is a copy, which is obviously detrimental to the performance. Of course, we can copy the code function Person (name, age) {this. name = name; this. age = age; this. getName = getName;} function getName () {return this. name;} var person1 = new Person ("hainan", 25); var person2 = new Person ("allenxing", 26); console. log (person1.getName = person2.getName); // copy the code to true. This means that each instance references the same function, so it is equal, but if there are many methods, we cannot define all functions in the global scope, which requires other modes to solve. We have discussed prototype and prototype chain before. Here we can simply learn this prototype. Copy the code function Person () {} Person. prototype = {constructor: Person, name: "hainan", getName: function () {return this. name} var person1 = new Person (); var person2 = new Person (); console. log (person1.getName = person2.getName); // copy the code in this way. The prototype mode solves the performance and memory problems that each instance in the constructor has a copy of the method, however, the prototype also has its own shortcomings: the attributes in the prototype are shared, which is both an advantage and a disadvantage. When the attribute is of the reference type, this problem is apparent. Copy the code function Person () {} Person. prototype = {constructor: Person, name: "hainan", friends: ["James"], getName: function () {return this. name} var person1 = new Person (); person1.friends. push ("Melo"); var person2 = new Person (); console. log (person2.friends); // "James", "Melo", copy the code and we can see that we have added a friend to person1. As a result, the friend of person2 has also been added, all instances share the attributes in the prototype. The combination mode (constructor and prototype) is the most common and recommended method. constructor is used to define instance attributes, and the prototype is used to specify methods and shared attributes, this will combine the advantages of the two modes. Each instance will have a copy of the Strength attribute and share the reference to the method, saving the memory. Copy the code function Person (name, age) {this. name = name; this. age = age; this. friends = ["James"];} Person. prototype = {constructor: Person, getName: function () {return this. name} var person1 = new Person ("hainan", 25); person1.friends. push ("Melo"); console. log (person2.friends); // "James", "Melo" var person2 = new Person ("allenxing", 26); console. log (person2.friends); // "James" copy the code dynamic prototype mode. The so-called dynamic prototype mode is to place the prototype mode and constructor mode in In the constructor, check whether this method exists before defining the method. If it does not exist, add this method to the prototype. Copy the code function Person (name, age) {this. name = name; this. age = age; if (typeof this. getName! = "Function") {Person. prototype. getName = function () {return this. name ;}} var person1 = new Person ("hainan", 25); var person2 = new Person ("allenxing", 26 ); in the copy code parasitic constructor mode book, we can use this mode if the previous few are not suitable. This mode is similar to the factory mode, they all encapsulate the process of creating an object into a function, but this mode uses the new operator. We will discuss the new operator in detail later. Copy the code function Person (name, age) {var obj = new Object (); obj. name = name; obj. age = age; return obj;} var person1 = new Person ("hainan", 25); var person2 = new Person ("allenxing", 26 ); copy the code using a constructor with a returned value. The returned value will overwrite the default returned value of the constructor. I will write an article about this. The secure object mentioned in the safe constructor pattern book is that there is no public attribute, and its method does not reference this object. Let's look at the example. Let's take a look at it in advanced programming, compared with the previous several types, we can see why it is secure. Copy the code function Person (name, age) {var obj = new Object (); obj. getName = function () {return name; // this}; return obj;} var person1 = Person ("hainan", 25) is not used; // newconsole is not used. log (person1.getName ());

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.