当前位置:网站首页>The interviewer asked: can you simulate the new operator of JS
The interviewer asked: can you simulate the new operator of JS
2022-06-28 02:11:00 【InfoQ】
1. Preface
JSnew、call、apply、this、 Inherit Interviewer asks series Vuejsnewnew Vue({
el: '#app',
mounted(){},
});
newnew2. new What did you do
// Example 1
function Student(){
}
var student = new Student();
console.log(student); // {}
// student It's an object .
console.log(Object.prototype.toString.call(student)); // [object Object]
// We know that we can also declare objects with new Object(); It just looks more complicated
// By the way `new Object`( Not recommended ) and Object() The same effect
// It can be guessed that an internal judgment has been made , use new call
/** if (!(this instanceof Object)) {
* return new Object();
* }
*/
var obj = new Object();
console.log(obj) // {}
console.log(Object.prototype.toString.call(student)); // [object Object]
typeof Student === 'function' // true
typeof Object === 'function' // true
newStudentObjectStudentObjectJS
new Object()new Student()__proto__constructorStudent// in other words :
student.constructor === Student;
Student.prototype.constructor === Student;
2.1 Summary 1: From this simple example ,
new
The operator does two things :
- A new object is created .
- This object will be executed
[[Prototype]]( That is to say__proto__) link .
// Example 2
function Student(name){
console.log(' Before assignment -this', this); // {}
this.name = name;
console.log(' After the assignment -this', this); // {name: ' If Chuan '}
}
var student = new Student(' If Chuan ');
console.log(student); // {name: ' If Chuan '}
Studentthisnew Student()student2.2 Summary 2: From this example ,
new
The operator does one more thing :
- The generated new object is bound to the function call
this.
// Example 3
function Student(name){
this.name = name;
// this.doSth();
}
Student.prototype.doSth = function() {
console.log(this.name);
};
var student1 = new Student(' if ');
var student2 = new Student(' sichuan ');
console.log(student1, student1.doSth()); // {name: ' if '} ' if '
console.log(student2, student2.doSth()); // {name: ' sichuan '} ' sichuan '
student1.__proto__ === Student.prototype; // true
student2.__proto__ === Student.prototype; // true
// __proto__ It is the prototype scheme of browser implementation .
// use ES5 It is :
Object.getPrototypeOf(student1) === Student.prototype; // true
Object.getPrototypeOf(student2) === Student.prototype; // true


2.3 Summary 3: This example 3 Once again
Summary 1
Medium
The first 2 spot
. That is, the object will be executed
[[Prototype]]
( That is to say
__proto__
) link . And through
new Student()
Each object created will eventually be
[[Prototype]]
Link to this
Student.protytype
On the object .
// Example 4
function Student(name){
this.name = name;
// Null( empty ) null
// Undefined( Undefined ) undefined
// Number( Numbers ) 1
// String( character string )'1'
// Boolean( Boolean ) true
// Symbol( Symbol )( New in the sixth edition ) symbol
// Object( object ) {}
// Function( function ) function(){}
// Array( Array ) []
// Date( date ) new Date()
// RegExp( Regular expressions )/a/
// Error ( error ) new Error()
// return /a/;
}
var student = new Student(' If Chuan ');
console.log(student); {name: ' If Chuan '}
{name: ' If Chuan '}ObjectFunctoinArrayDateRegExgError2.4 The resulting Summary 4:
- If the function does not return an object type
Object( containFunctoin,Array,Date,RegExg,Error), thatnewThe function call in the expression automatically returns the new object .
- A new object is created .
- This object will be executed
[[Prototype]]( That is to say__proto__) link .
- The generated new object is bound to the function call
this.
- adopt
newEach object created will eventually be[[Prototype]]Linked to this functionprototypeOn the object .
- If the function does not return an object type
Object( containFunctoin,Array,Date,RegExg,Error), thatnewThe function call in the expression automatically returns the new object .
3. new Simulation Implementation
new/**
* Simulation Implementation new The operator
* @param {Function} ctor [ Constructors ]
* @return {Object|Function|Regex|Date|Error} [ Return results ]
*/
function newOperator(ctor){
if(typeof ctor !== 'function'){
throw 'newOperator function the first param must be a function';
}
// ES6 new.target Is pointing to the constructor
newOperator.target = ctor;
// 1. Create a new object ,
// 2. And perform [[Prototype]] link
// 4. adopt `new` Each object created will eventually be `[[Prototype]]` Linked to this function `prototype` On the object .
var newObj = Object.create(ctor.prototype);
// ES5 arguments Turn it into an array You can also use it ES6 [...arguments], Aarry.from(arguments);
// remove ctor The rest of the arguments to the constructor
var argsArr = [].slice.call(arguments, 1);
// 3. The generated new object is bound to the function call `this`.
// Get ctor Function returns the result
var ctorReturnResult = ctor.apply(newObj, argsArr);
// Summary 4 Of these types, only Object and Function Two types of typeof null It's also 'object' So it's not equal to null, exclude null
var isObject = typeof ctorReturnResult === 'object' && ctorReturnResult !== null;
var isFunction = typeof ctorReturnResult === 'function';
if(isObject || isFunction){
return ctorReturnResult;
}
// 5. If the function does not return an object type `Object`( contain `Functoin`, `Array`, `Date`, `RegExg`, `Error`), that `new` The function call in the expression automatically returns the new object .
return newObj;
}
newOperator// Example 3 Add one more parameter
function Student(name, age){
this.name = name;
this.age = age;
// this.doSth();
// return Error();
}
Student.prototype.doSth = function() {
console.log(this.name);
};
var student1 = newOperator(Student, ' if ', 18);
var student2 = newOperator(Student, ' sichuan ', 18);
// var student1 = new Student(' if ');
// var student2 = new Student(' sichuan ');
console.log(student1, student1.doSth()); // {name: ' if '} ' if '
console.log(student2, student2.doSth()); // {name: ' sichuan '} ' sichuan '
student1.__proto__ === Student.prototype; // true
student2.__proto__ === Student.prototype; // true
// __proto__ It is the prototype scheme of browser implementation .
// use ES5 It is :
Object.getPrototypeOf(student1) === Student.prototype; // true
Object.getPrototypeOf(student2) === Student.prototype; // true
newnewnewOperatorObject.create()ES5API4. Object.create() Usage example
Object.create(proto, [propertiesObject])undefinedvar anotherObject = {
name: ' If Chuan '
};
var myObject = Object.create(anotherObject, {
age: {
value:18,
},
});
// Get its prototype
Object.getPrototypeOf(anotherObject) === Object.prototype; // true explain anotherObject The prototype is Object.prototype
Object.getPrototypeOf(myObject); // {name: " If Chuan "} // explain myObject The prototype is {name: " If Chuan "}
myObject.hasOwnProperty('name'); // false; explain name It's a prototype .
myObject.hasOwnProperty('age'); // true explain age It's self
myObject.name; // ' If Chuan '
myObject.age; // 18;
ES5MDNployfillif (typeof Object.create !== "function") {
Object.create = function (proto, propertiesObject) {
if (typeof proto !== 'object' && typeof proto !== 'function') {
throw new TypeError('Object prototype may only be an Object: ' + proto);
} else if (proto === null) {
throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument.");
}
if (typeof propertiesObject != 'undefined') throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument.");
function F() {}
F.prototype = proto;
return new F();
};
}
5. So to conclude :
newWhat did you do :
- A new object is created .
- This object will be executed
[[Prototype]]( That is to say__proto__) link .
- The generated new object is bound to the function call
this.
- adopt
newEach object created will eventually be[[Prototype]]Linked to this functionprototypeOn the object .
- If the function does not return an object type
Object( containFunctoin,Array,Date,RegExg,Error), thatnewThe function call in the expression automatically returns the new object .
- How to simulate
// Removed comments
function newOperator(ctor){
if(typeof ctor !== 'function'){
throw 'newOperator function the first param must be a function';
}
newOperator.target = ctor;
var newObj = Object.create(ctor.prototype);
var argsArr = [].slice.call(arguments, 1);
var ctorReturnResult = ctor.apply(newObj, argsArr);
var isObject = typeof ctorReturnResult === 'object' && ctorReturnResult !== null;
var isFunction = typeof ctorReturnResult === 'function';
if(isObject || isFunction){
return ctorReturnResult;
}
return newObj;
}
边栏推荐
- Data analysts too hot? Monthly income 3W? Tell you the true situation of this industry with data
- Jenkins - Pipeline 语法
- The research group of Xuyong and duanwenhui of Tsinghua University has developed an efficient and accurate first principles electronic structure deep learning method and program
- Machine learning notes - time series as features
- 基于可学习尺寸自适应分子亚结构的药物相互作用预测
- JS random number (random number decimal)
- [Yocto RM]1 - System Requirements
- Numpy----np. reshape()
- 数据库查询优化:主从读写分离及常见问题
- 机器学习笔记 - 时间序列作为特征
猜你喜欢

What is digitalization? What is digital transformation? Why do enterprises choose digital transformation?

Chapitre 4: redis

Cesium 多边形(polygon)extrudedHeight 和 height 的区别

Jenkins - Pipeline 语法

Overview of drug discovery-01 overview of drug discovery

一张图弄懂 MIT,BSD,Apache几种开源协议之间的区别

Database query optimization: master-slave read-write separation and common problems

Maimai hot post: Why are big factories keen on making wheels?

【牛客討論區】第四章:Redis

How to understand query, key and value in transformer
随机推荐
Scala 基础 (三):运算符和流程控制
Adobe Premiere基础-声音调整(音量矫正,降噪,电话音,音高换挡器,参数均衡器)(十八)
Hi, you have a code review strategy to check!
What are the risks of opening a compass stock account? Is it safe to open a compass account
学习 pickle
Cesium Color 颜色(赋值)随机颜色
Adobe Premiere基础-编辑素材文件常规操作(脱机文件,替换素材,素材标签和编组,素材启用,便捷调节不透明度,项目打包)(十七)
[Yocto RM] 4 - Source Directory Structure
Adobe Premiere Basics - common video effects (cropping, black and white, clip speed, mirroring, lens halo) (XV)
pytorch_lightning.utilities.exceptions.MisconfigurationException: You requested GPUs: [1] But...
TIA botu_ Concrete method of making analog input and output Global Library Based on SCL language
【ELT.ZIP】OpenHarmony啃论文俱乐部—数据密集型应用内存压缩
药物发现综述-03-分子设计与优化
MySQL十种锁,一篇文章带你全解析
Maimai hot post: Why are big factories keen on making wheels?
Cesium 多边形增加文字标签(polygon 加 label)多边形中心点偏移问题解决
Prometeus 2.35.0 新特性
Database query optimization: master-slave read-write separation and common problems
[Yongyi XY chair] trial experience
How to study efficiently