Object, class, and object oriented programming
- Attribute types - these are the standard definitions of the js internal engine and cannot be changed
It is divided into data attribute and accessor attribute
[[Configurable]] whether it can be deleted and redefined through delete, whether its characteristics can be modified, and whether it can be changed into an accessor attribute. The default is true
[[Enumerable]] indicates whether the attribute can be returned through a for in loop. The attribute directly defined in the attribute of the object is true
[[Writable]] indicates whether the value of the property can be modified. The default value is true
[[Value]] contains the actual Value of the property. The read and write locations are undefined by default
/*To modify the default properties of the default properties You must use object The defineproperty () method receives three parameters The object to which you want to add properties The name of the property A descriptor object (the attribute on the descriptor object contains) configurable\enumerable\writable\value It corresponds to the name of the related property one by one. You can set one or more of these values depending on the properties you want to modify */ let person = {}; Object.defineProperty((person,"name",{ writable:false, value:"Nicholas" })); console.log(person.name); person.name = 'Greg'; console.log(preson.name)//Nicholas delete person.name; //Similar rules apply to creating non configurable properties console.log(preson.name)//Nicholas /* Accessor properties Accessor properties do not contain data values. They contain gtter setter functions. These two functions are not necessary. [[Configurable]] Indicates whether the attribute can be deleted and redefined through delete, whether its characteristics can be modified, and whether it can be changed into a data attribute. By default, this property is true [[Enumerable]] Whether it can be returned through the for in loop. Default true [[Get]] Get the function, which is called when reading the attribute. The default value is undefined [[Set]] Set the function, which is called when writing properties. The default is undefined */ /* Accessor properties cannot be defined directly. You must use object defineProperty() */ //Define an object that contains the pseudo private member year_ That public member edition let book = { year_:2017, edition:1 }; Object.defineProperty(book,"year",{ get() { return this.year_; }, set(newValue) { if(newValue > 2017) { this.year_ = newValue; this.edition += newValue - 2017; } } }) book.year = 2018; console.log(book.edition);// 2 // /* Define multiple attributes Object.defineProperties() This method can define multiple attributes at one time through multiple descriptors 2 Parameter, (the object for which the attribute is to be added or modified, another descriptor object whose attribute corresponds to the attribute to be added or modified one by one.) */ let look = {}; Object.defineProperties(book,{ year_:{ value:2017 }, edition:{ value:1 }, year:{ get(){ return this.year_; }, set(newValue) { if(newValue >2017) { this.year_ = newValue; this.edition += newValue - 2017; } } } })
/** Object.getOwnPropertyDescriptor() * read attribute * @param {obj} The object on which the object property is located * @param {str} String the property name whose descriptor you want to get * @param {obj} The returned object has different properties according to different property types */ let book = {}; Object.defineProperties(book,{ year_:{ value:2017 }, edition:{ value:1 }, year: { get: function() { return this.year_; }, set: function(newValue){ if(newValue > 2017) { this.year_ = newValue; this.edition += newValue - 2017; } } } }) let descriptor = Object.getOwnPropertyDescriptor(book,"year_"); /* */ console.log(Object.getOwnPropertyDescriptors(book)); //es2017's method will call object on each of its own attributes Getownpropertydescriptor () and return them in a new object
/** * merge * * assign() * @param {obj} Returns one or more objects * * First put each original object object Propertyisenumerable() returns true * And own objects Hasownproperty() returns true) the property is copied to the target object * Use the get of the original object and the set of the target object * * The operation on an object is a shallow copy. If multiple source objects have the same properties, the value of the last copy is used */ let dest,src,result; dest = {id:'dest'}; result = Object.assign(dest,{id:'src1',a:'foo'},{id:'src2',b:'bar'}); //The same properties as before will be overwritten console.log(reslut);//{ id: src2, a: foo, b: bar } // The process of overwriting can be observed through the setting function on the target object: dest = { set id(x) { console.log(x); } }; Object.assign(dest, { id: 'first' }, { id: 'second' }, { id: 'third' }); // first // second // third let dest ,src ,result; /** * error handling */ dest = {}; src = { a: 'foo', get b () { //Object.assign() will throw an error when calling this get function throw new Error(); }, c:'bar' }; try{ Object.assign(dest,src) } catch(e) { } // Object.assign() cannot roll back the completed modification // Therefore, the completed modifications on the target object will continue until the error is thrown: console.log(dest); // { a: foo }
//Object identification and equality determination //These are = = = as expected console.log(true === 1); // false console.log({} === {}); // false console.log("2" === 2); // false // These situations behave differently in different JavaScript engines, but are still considered equal console.log(+0 === -0); // true console.log(+0 === 0); // true console.log(-0 === 0); // true // To determine the equality of NaN, the extremely annoying isNaN() must be used console.log(NaN === NaN); // false console.log(isNaN(NaN)); // true //ES6 adds object Is () and = = = are similar /** * Judge whether they are equal * * is() * @param {obj} Pass 2 objects * */ console.log(Object.is(true, 1)); // false console.log(Object.is({}, {})); // false console.log(Object.is("2", 2)); // false // Correct 0, - 0, + 0 equal / unequal judgment console.log(Object.is(+0, -0)); // false console.log(Object.is(+0, 0)); // true console.log(Object.is(-0, 0)); // false // Correct NaN equality determination console.log(Object.is(NaN, NaN)); // true //If you want to check multiple values, you can pass them recursively using equality function recursivelyCheckEqual(x,...rest){ return Object.is(x,rest[0]) && (rest.lengt < 2 || recursivelyCheckEqual(...rest)) }
es6 attribute value abbreviation
let name = 'Matt'; let person = { //name:name name };
es6 computable attributes
//This is required to dynamically define the object key value before old const namekEY = 'name'; const ageKey = 'age'; let person = {}; person[nameKey] = 'Matt'; person[ageKey] = 27; console.log(person) // {name:'Matt',age:27} //New ES6 can now be defined dynamically let person = { [nameKey]: 'Matt', [ageKey]: 27 };
es6 abbreviated method name
//old es5 let person = { sayName: function() { console.log('...') } } person.sayName('Matt');//My name is Matt //new es6 const methodKey = 'sayName'; let person = { sayName(name) { console.log('...') } [methodKey](name) {// Short method names are compatible with computable attribute keys console.log('1212') } }
//The fit calculation attribute itself can be a complex expression const nameKey = 'name'; const ageKey = 'age'; const jobKey = 'job'; let uniqueToken = 0; function getUniqueKey(key) { return `${key}_${uniqueToken++}`; } let person = { [getUniqueKey(nameKey)]: 'Matt', [getUniqueKey(ageKey)]: 27, [getUniqueKey(jobKey)]: 'Software engineer' }; console.log(person); // { name_0: 'Matt', age_1: 27, job_2: 'Software engineer' }
Object deconstruction
1. Deconstruction of the same name can be omitted
2. Deconstruction can structure object properties and methods to convert the source data structure into an object, but null and undefined cannot be deconstructed
3. Deconstruction can be performed at the same time, and the default value can be defined
4. Deconstruction does not require that the variable must be declared in the deconstruction expression. If it is declared in advance, the deconstruction expression must be contained in a pair of parentheses
5. Nested deconstruction there are no restrictions on nested attributes or assignment targets. You can copy object attributes (shallow copy)
6. Nested deconstruction can use nested structure for deconstruction
7. The nested deconstruction outer attribute is not defined, and the source object / target object cannot be used
8. Object deconstruction. If an error occurs during the deconstruction, only part of the object will be deconstructed
9. The object is deconstructed in the function parameter list and will not affect the arguments
let person = { name:'Matt', age:27 }; let {name, age} = person; console.log(name); //Matt console.log(age); //27
//Default values can be defined at the same time during deconstruction let person = { name:'Matt', age: 27 }; let {name,job='Software engineer'} = person; console.log(name); //Matt console.log(job); //Software engineer
Several methods of creating objects
Factory mode
- Popular application in software engineering
function createPerson(name,age,job) { let o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function () { console.log(this.name); } return o; } let person1 = createPerson('nicholas',29,"Software Engineer"); let person2 = createPerson('Greg',28,"Doctor");
function Person(name,age,job) { this.name = name; this.age = age; this.job = job; this.sayName = function () { console.log(this.name) } } let person1 = new Person('Nicholas',12,"student") let person2 = new Person('Jack',11,"police")
What does the new operator do
(1) Create a new object in memory.
(2) The [[prototype]] attribute inside the new object is assigned to the prototype attribute of the constructor.
(3) This inside the constructor is assigned to the new object (that is, this points to the new object).
(4) Execute the code inside the constructor (add properties to the new object).
(5) If the constructor returns a non empty object, the object is returned; Otherwise, the new object just created is returned.
This is the note I took when I was studying at the class bar. It was very good. We broadcast the class together. The teacher was humorous, the thief was funny and easy to understand. It's awesome. I love it. After class, everyone in the wechat group communicates very actively. The little sister of the teaching assistant teaches patiently. Ha ha ha
The following is a screenshot of my class