1. How can I create an object and set its property age to 18?
let a = {name: "haha"};
Object.defineProperty(a, "age", {
configurable: false.value: 18,})console.log(a) // {name: "haha", age: 18}
delete a.name
delete a.age
console.log(a) //{age: 18}
Copy the code
General attributes are divided into data attributes and accessor attributes. There are four attributes in data attributes:
-
[[64x]] Specifies whether a new device can be deleted by delete
- Once a property is defined as unconfigurable, it cannot be changed back to configurable.
-
[[Enumerable]] can be returned in a for-in loop
-
[[Writeable]] indicates whether the attribute can be modified
-
[[Value]] Contains the Value of the attribute
2. How to add methods to this object so that when you change the year property, if the value is greater than 2017, change _year and change edition = edition – 2017.
let book = {
year_: 2018.edition: 1
}
// TODO
book.year = 2019
console.log('book', book); // book { year_: 2019, edition: 2 }
Copy the code
Object.defineProperty(book, "year", {get() {
return this.year_;
},
set(newValue) {
if(newValue > 2017) {
this.year_ = newValue;
this.edition = newValue - 2017}}})Copy the code
Accessors do not contain data values, but instead contain a function to get getters and set setters.
- [[64x]] Specifies whether a new device can be deleted by delete
- [[Enumerable]] can be returned in a for-in loop
- [[Get]] Gets the function, called when reading properties
- [[Value]] Sets the function, which is called when the function is written
Accessors must use Object.defineProperty() and cannot be defined directly
3. How to read the property descriptor of an object?
let a = {};
Object.defineProperty(a, "age", {
configurable: false.value: 18,})// TODO gets the property descriptor for age
Copy the code
let description = Object.getOwnPropertyDescriptor(a, "age");
console.log("description", description)
Copy the code
Object. GetOwnPropertyDescriptor () can get attributes of the specified descriptor. ES7 are Object. The new getOwnPropertyDescriptors () static method, and get all the own properties of an Object descriptor.
4. For merging objects, write the result of the following code.
let src , dest, result ;
dest = {id: 'dest'}
src = Object.assign(dest, {id: 'src1,' ,a: 'foo'}, {id: 'src2'.b: 'bar'.c: {}})
console.log('src', src);
console.log('flag', src.c === dest.c)
Copy the code
src {id: "src2".a: "foo".b: "bar".c: {}}
flag true
Copy the code
- Object.assign, parameters for the target Object and multiple source objects, Each source Object can be enumerated (Object) propertyIsEnumerable () to true) properties and has its own properties (Object. The hasOwnProperty to true) is copied to the target Object.
- If there are multiple source objects with the same property, only the last one is copied.
- Shallow copy, which copies only references to objects
- If an error occurs during replication, only part of the replication will be completed.
5. How to correctly determine whether an object is the same, and how to determine +0,-0,NaN.
function compare(a, b) {
}
compare(NaN.NaN) // true
compare(+0, -0) // false
compare(+0.0) // true
compare({}, {}) // false
compare(true.1) // false
Copy the code
function compare(a, b) {
return Object.is(a, b)
}
Copy the code
6. How to simplify the following code
let name = "haha";
let person = {
name: name,
sayName: function(name) {
console.log('my name is '+ name); }}Copy the code
let name = "haha";
let person = {
name,
sayName(name) {
console.log('my name is '+ name); }}Copy the code
Enhance the syntax of objects
- Attribute shorthand
- Computable attribute
const nameKey = 'age';
let person = {
[nameKey]: 18
}
Copy the code
- Short method name
7. Write the result of the following code
let person = {
name: "haha".age: 18
};
const {age,name,job,other="otherthings"} = person;
console.log("age", age);
console.log("name", name);
console.log("job", job);
console.log("other", other);
let {length} = 'fooo';
console.log('length', length);
let {constructor: c} = 4;
console.log(c === Number)
let { s } = null;
let { s2 } = undefined;
Copy the code
age 18
name haha
job undefined
other otherthings
length 4
true
VM274:18 Uncaught TypeError: Cannot destructure property 's' of 'null' as it is null.
at <anonymous>:18:7
Copy the code
ES6 has a new object deconstruction syntax that allows you to use its set of data to implement one or more assignment operations in a single statement.
- Assignment does not necessarily match an object attribute; it is undefined if the referenced attribute does not exist
- You can also define default values while deconstructing assignments
Inside the deconstruction, the function ToObject()(not accessible in the function runtime environment) is used to deconstruct the source data into objects. Meaning that in the context of object deconstruction, the original value is treated as an object, meaning (as defined by ToObject()) that null and undefined cannot be deconstructed or an error will be thrown.
8. Write the output of the following code
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("p1".18."teacher")
let person2 = new Person("p2".27."doctor")
person1.sayName();
person2.sayName();
console.log(person1.sayName == person2.sayName)
console.log(person1.constructor == Person)
console.log(person2.constructor == Person)
console.log(person1 instanceof Object)
console.log(person2 instanceof Object)
console.log(person1 instanceof Person)
console.log(person2 instanceof Person)
Copy the code
/ / the result
p1
p2
false
true
true
true
true
true
true
Copy the code
When we create an object using a constructor, we say:
- The object is created without showing it
- Properties and methods are assigned directly to this
- There is no return
How to implement new
- Create a new object in memory
- The [[prototype]] property inside the entire new object is assigned to the constructor’s prototype property
- The constructor assigns this internally to the new object (that is, this refers to the new object)
- Execute the code inside the constructor (add attributes to the new object)
- If the constructor returns a non-empty object, that object is returned; otherwise, the newly created object is returned.
The constructor and instance
- Constructor is used to identify the type of object.
- Instanceof is a more reliable way to determine object types
- Each Object is an instance of Object as well as an instance of Person.
A few questions
- Does the instance object always have a constructor pointing to the constructor?
- Does the instance point to whom it was created?
- Can person1.constructor point to an object? Object
Constructors and ordinary functions
- The only difference is how it is called. Any function called with the new operator is a constructor
Constructor problem
- The method defined by the constructor is created again on each instance.
- Functions are objects, and each time a function is defined, an object is initialized.
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function() {
console.log(this.name)
}
// it is equivalent to the following
this.sayName = new Function("console.log(this.name)")}Copy the code
- So person1.sayName and person2.sayName have the same name but are not the same.
9. Write the output of the following code
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype.sayName = function() {
console.log('name'.this.name)
}
let person1 = new Person("p1".18."teacher")
let person2 = new Person("p2".27."doctor")
person1.sayName();
person2.sayName();
console.log(person1.sayName == person2.sayName)
Copy the code
name p1
name p2
true
Copy the code
The prototype pattern
- Each function creates a Prototype property, which is an object containing properties and methods shared by instances of a particular reference type.
- In effect, this object is a prototype created by calling the constructor.
- Whenever a function is created, a Prototype attribute (pointing to the prototype object) is created for that function according to certain rules
- By default, all stereotype objects automatically get a property called constructor that points back to the constructor associated with them
- In the case of custom constructors, the stereotype Object returns only the constructor property by default; all other methods inherit from Object
- Each time the constructor is called to create a new instance, the inner [[prototype]] pointer of that instance returns the prototype object assigned to the constructor.
The problem
- There is a direct connection between the instance and the constructor stereotype, but not between the instance and the constructor.
Write down the following results
function Person() {}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function() {
console.log(this.name);
};
let person1 = new Person();
let person2 = new Person();
person1.name = "Greg";
console.log(person1.name);
console.log(person2.name);
delete person1.name;
console.log(person1.name);
Copy the code
console.log(person1.name); // "Greg" - from instance
console.log(person2.name); // "Nicholas" - from prototype
delete person1.name;
console.log(person1.name); // "Nicholas" - from the prototype
Copy the code
- When a property is accessed through an object, the object instance itself is searched and returned if it is found. If not, the prototype object is followed by a pointer and the value is returned.
- Add a property to the object instance that overshadows the property of the same name on the prototype object.
- Even if the property is set to NULL, the connection is not restored, but the property can be completely removed by DELETE, allowing identifier resolution to continue searching the object.
11. Object.create
let biped = {
numLegs: 2
}
let person = Object.create(biped);
person.name = "Matt"
console.log(person.name)
console.log(person.numLegs)
console.log(Object.getPrototypeOf(person) === biped)
Copy the code
Matt
2
true
Copy the code
Object.create creates a new Object and assigns a prototype to it.
Write down the following results
function Person() {}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function() {
console.log(this.name);
};
let person1 = new Person();
console.log(person1.hasOwnProperty("name"));
console.log("name" in person1);
let keys = Object.keys(Person.prototype);
console.log(keys);
p1.name = "Rob";
p1.age = 31;
let p1keys = Object.keys(p1);
console.log(p1keys);
Copy the code
console.log(person1.hasOwnProperty("name")); // false
console.log("name" in person1); // true
console.log(keys); // "name,age,job,sayName"
console.log(p1keys); // "name,age"
Copy the code
Two ways to make the operator of in
- Use alone and in for-ins
- In returns this property because on the object, both stereotype and instance properties return true
hasOwnProperty
- Returns true only if the property exists on an instance
Object properties
- For in, all properties that can be enumerated through the object model are returned, including instance and stereotype properties
- Properties in the shadowing stereotype whose [[Enumerable]] property is set to false are also returned in the for-in loop
- Gets all enumerable instance properties of an Object using object.keys
- List all Object instance attributes, whether or not can use enumeration Object. GetOwnPropertyNames ()
- ES7 also added two methods object.values () and object.entries ()
The constructor change does not affect instanceof
Write the following code
function Person() {}
let friend = new Person();
Person.prototype = {
constructor: Person,
name: "Nicholas".age: 29.job: "Software Engineer".sayName() {
console.log(this.name); }}; friend.sayName();Copy the code
VM73:15 Uncaught TypeError: friend.sayName is not a function
at <anonymous>:15:8
Copy the code
The dynamics of prototypes
- The search value of the prototype is dynamic, the prototype exists before the instance is modified, and any changes made to the prototype object are immediately reflected
- Overwriting a Prototype is not the same as adding a method. The [[Prototype]] pointer to an instance is automatically assigned when the constructor is called and does not change even when the object is changed to a different object. Rewriting the entire stereotype disconnects the original stereotype from the constructor.
A prototype of a native object
- Constructors of all stereotype reference types (Object,Array,String) define instance methods on the stereotype.
- All default method references can be obtained from a prototype of a native object, and new methods can be defined for instances of a native type. You can modify native object prototypes just as you can modify custom object prototypes, so you can modify the add method at any time.
- Like strings, when a property is read, the background automatically adds a wrapped instance of String to find the method call on String.prototype.
When to wrap an instance?
14. Prototype chain problems
function SuperType(name){
this.property = true
}
SuperType.prototype.getSuperValue = function() {
return this.property
};
function SubType(){
this.subProperty = false
}
// inherit methods
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function() {
return this.subProperty
};
let instance1 = new SubType();
console.log(instance.getSuperValue())
Copy the code
The idea of inheritance
- Inheriting properties and methods of multiple reference types through stereotypes
- Each constructor has a property object, the stereotype has a property pointing back to the constructor, and the instance has a pointer inside to the stereotype
- What if a stereotype is an instance of another type? That means that the entire stereotype itself has an internal pointer to another stereotype, which in turn has a pointer to another constructor. This creates a chain of stereotypes between the instance and the stereotype.
The default prototype
-
By default, all reference types inherit from Object.
-
The default prototype for any function is an instance of Object. That is, this instance has an internal pointer to Object.prototype
15. How to implement a parasitic composite inheritance
function obejct(o) {
function F(){}
F.prototype = o;
return new F();
}
function inheritPrototype(subType, superType) {
let prototype = object(superType.prototype); // create object
prototype.constructor = subType; // augment object
subType.prototype = prototype; // assign object
}
function SuperType(name) {
this.name = name;
this.colors = ["red"."blue"."green"];
}
SuperType.prototype.sayName = function() {
console.log(this.name);
};
function SubType(name, age){
SuperType.call(this, name); // second call to SuperType()
this.age = age;
}
inheritPrototype(SubType, SuperType)
SubType.prototype.sayAge = function() {
console.log(this.age);
};
Copy the code
-
The instance method super.call inherits from the parent class
- Calls the parent class’s constructor in the subclass’s constructor. Because functions are really simple objects that execute code in a particular context
-
Primitive inheritance: You have an object and want to create another object on top of the existing one.
- ES5 new object.create ()
-
Super.prototype = new SuperType()
- This results in the parent class’s constructor always being used twice, once when the subclass stereotype is created and once when the subclass constructor is created.
-
The inheritPrototype method is implemented using a prototype copy of the parent class.
Class 16.
Definition of ascension
- Function declarations can be promoted, but class definitions cannot
Constitute a
- The constructor
- Instance methods
- Get function get
- Set function set
- Static method static
Class constructor and function constructor
- Class constructors must be called using new, and ordinary constructors that do not use new take the global this as their ordinary object
- Calling a class without new throws an exception
- Constructor defined in the class is not treated as a constructor, and using instanceof on it returns false. However, instanceof is different if the class constructor is used as a normal constructor for instance creation.
17. Class syntax
Instance members
Each time a class is called through new, the constructor of the class is executed. Inside the function, a new instance of this is created, adding its own attributes.
Each instance corresponds to a unique member object.
Prototype methods and accessors
Everything defined in a class block is defined on the prototype of the class
You cannot add raw values or objects as member data to a prototype in a class block
A static method
There is only one static member on each class.
Static members of this refer to the province of the reference class
Non-function archetypes and class members
Can be defined outside the class
Iterator and generator methods
The class definition syntax supports defining generator methods in the stereotype and in the class itself
18. The inheritance
Realize the basic
This is done through extends
Constructors and HomeObject and super ()
- A call to super in a static method can inherit a method defined on a class
Super points to note
- Only used in derived class constructors and static methods
- You cannot refer to the super keyword alone, either by calling the constructor or by referring to its static method
- Calling super() calls the function constructed by the parent class and assigns the returned instance to this
- In class constructors, you cannot refer to this before super()
- If a constructor is explicitly defined in a derived class, then either super() must be called in it, or an object must be returned in it.
Abstract base class
- It can be inherited by other classes, but is not instantiated itself
- Through the new target
Inheriting built-in types
Class with
- The extends keyword is followed by a Javascript expression. Any expression that can be resolved to a class or a constructor is valid.