Object.creat()
Syntax
Object. The create (proto, [propertiesObject])Copy the code
- proto
The prototype object of the newly created object.
- propertiesObject
Optional. You need to pass in an Object whose property type refers to the second parameter of Object.defineProperties().
- Return value: a new object
An example:
Construct an object with only one property width ->square
let squareList = []
let widthList = [5.6.5.6.5.6.5.6.5.6.5.6]
// constructor
function createSquare(width){
// Create an empty object using squarePrototype
let obj = Object.create(squarePrototype)
obj.width = width
return obj
}
let squarePrototype = {
getArea(){
return this.width * this.width
},
getLength(){
return this.width * 4}}for(let i = 0; i<12; i++){
squareList[i] = createSquare(widthList[i])
// Create a square.
}
Copy the code
Functions and prototypes are combined
let squareList = []
let widthList = [5.6.5.6.5.6.5.6.5.6.5.6]
function createSquare(width){
let obj = Object.create(createSquare.squarePrototype) // Use it before you define it. NO
obj.width = width
return obj
}
createSquare.squarePrototype = { // Put the prototype on the function. Is the combination tight enough?
getArea(){
return this.width * this.width
},
getLength(){
return this.width * 4
},
constructor: createSquare // Make it easy to find the constructor through the prototype
}
for(let i = 0; i<12; i++){
squareList[i] = createSquare(widthList[i])
console.log(squareList[i].constructor)
// Constructor can know who constructed this object -> createSquare
}
Copy the code
New operator
let squareList = []
let widthList = [5.6.5.6.5.6.5.6.5.6.5.6]
function Square(width){
this.width = width
}
Square.prototype.getArea = function(){
return this.width * this.width
}
Square.prototype.getLength = function(){
return this.width * 4
}
for(let i = 0; i<12; i++){
squareList[i] = new Square(widthList[i])
console.log(squareList[i].constructor)
}
Copy the code
prototype
Object.__proto__ === its constructor. Prototype
The only exception: Object.prototype.__proto__ === null