当前位置:网站首页>Call, apply, bind rewrite, easy to understand with comments
Call, apply, bind rewrite, easy to understand with comments
2022-07-06 06:46:00 【Carpool steed】
Don't talk too much nonsense, just go to the code , Please point out any errors and problems
call Realization
;(() => {
Function.prototype.myCall = function (ctx) {
ctx = ctx ? Object(ctx) : window
// take Add an object above the parameter object , So make sure that ctx It's the object
ctx.pointer = this
// Declare an empty array
const param = []
for (let i = 1; i < arguments.length; i++) {
param.push(`arguments[${
i}]`)
}
// Receive the return value of the next norm
const ret = eval(`ctx.pointer(${
param.toString()})`)
// Delete the newly added attribute above
delete ctx.pointer
// Go back out again
return ret
}
// test
function test() {
console.log(this, arguments)
return 'value'
}
test.myCall({
a: 1, b: 2 }, ' Parameters 1', ' Parameters 2')
})()
apply Realization
;(() => {
Function.prototype.myApply = function (ctx, args) {
ctx = ctx ? Object(ctx) : window
let ret
// take Add an object above the parameter object , So make sure that ctx It's the object
ctx.pointer = this
// Judge args type
const type = Object.prototype.toString.call(args).slice(8, -1)
if (type === 'Array') {
// Receive the return value of the next norm , utilize ... Expand expression expand parameter
ret = eval('ctx.pointer(...args)')
// Delete the newly added attribute above
delete ctx.pointer
} else if (
type === 'Null' ||
type === 'Undefined' ||
type === 'Function'
) {
ret = eval('ctx.pointer()')
// Delete the newly added attribute above
delete ctx.pointer
} else {
throw new TypeError('CreateListFromArrayLike called on non-object')
}
// Go back out again
return ret
}
// test
function test() {
console.log(this, arguments)
return 'value'
}
test.myApply({
a: 1, b: 2 }, function () {
})
})()
bind Realization : This is a bit hard to understand , Just look at the note number
// characteristic :
// 1 . Returns a new function
// 2. bind -> The first parameter -> change this Point to
// 3. Receive parameter separation
// 4.bind and call Function parameters are passed in the same way
// 5. Instantiate the new function returned -> this. The point is test Constructed instance
// 6. Instances should inherit test Prototype on constructor
Function.prototype.myBind = function (ctx) {
// 1. preservation this
const pointer = this
// 2. Parameters passed for the first time
const params = [].slice.call(arguments, 1)
// Create a new intermediate function for Assignment prototype
const _typeFn = function () {
}
// Return new function
const newFn = function (param) {
// 3.param Parameters passed for the second time utilize concat Splicing
const args = params.concat(param)
// 4. Call function If test If there is a return value, you need to return 5. Judge this
return pointer.apply(this instanceof newFn ? this : ctx, args)
}
// 6. Copy prototype
_typeFn.prototype = pointer.prototype
newFn.prototype = new _typeFn()
return newFn
}
// test
function test(user, car) {
console.log(this)
console.log(user + ' Just bought one ' + car + ' vehicle ')
}
test.prototype.fun = ' Method '
const t = test.myBind({
a: 1, b: 2 }, ' Zhang San ')
const t1 = new t(' Mercedes ')
console.log(t1)
Try to integrate ideas into development , cheer up !!!
边栏推荐
- 成功解决AttributeError: Can only use .cat accessor with a ‘category‘ dtype
- SSO process analysis
- [Yu Yue education] Dunhuang Literature and art reference materials of Zhejiang Normal University
- It is necessary to understand these characteristics in translating subtitles of film and television dramas
- Do you really know the use of idea?
- Leetcode daily question (971. flip binary tree to match preorder traversal)
- How to do a good job in financial literature translation?
- CS-证书指纹修改
- [English] Grammar remodeling: the core framework of English Learning -- English rabbit learning notes (1)
- [ 英语 ] 语法重塑 之 英语学习的核心框架 —— 英语兔学习笔记(1)
猜你喜欢
A method to measure the similarity of time series: from Euclidean distance to DTW and its variants
How much is it to translate Chinese into English for one minute?
[web security] nodejs prototype chain pollution analysis
如何做好互联网金融的英语翻译
如何做好金融文献翻译?
论文翻译英译中,怎样做翻译效果好?
Today's summer solstice
Market segmentation of supermarket customers based on purchase behavior data (RFM model)
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models.common‘ from ‘/home/yolov5/models/comm
专业论文翻译,英文摘要如何写比较好
随机推荐
Pallet management in SAP SD delivery process
Day 246/300 SSH connection prompt "remote host identification has changed!"
What are the commonly used English words and sentences about COVID-19?
CS passed (cdn+ certificate) PowerShell online detailed version
MySQL high frequency interview 20 questions, necessary (important)
Py06 字典 映射 字典嵌套 键不存在测试 键排序
国产游戏国际化离不开专业的翻译公司
Making interactive page of "left tree and right table" based on jeecg-boot
Brief introduction to the curriculum differences of colleges and universities at different levels of machine human major -ros1/ros2-
The internationalization of domestic games is inseparable from professional translation companies
Day 248/300 thoughts on how graduates find jobs
How to convert flv file to MP4 file? A simple solution
Luogu p2141 abacus mental arithmetic test
Machine learning plant leaf recognition
机器学习植物叶片识别
Thesis abstract translation, multilingual pure human translation
翻译生物医学说明书,英译中怎样效果佳
国际经贸合同翻译 中译英怎样效果好
ML之shap:基于adult人口普查收入二分类预测数据集(预测年收入是否超过50k)利用Shap值对XGBoost模型实现可解释性案例之详细攻略
Is it difficult for girls to learn software testing? The threshold for entry is low, and learning is relatively simple