当前位置:网站首页>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 !!!
边栏推荐
- Engineering organisms containing artificial metalloenzymes perform unnatural biosynthesis
- Lecture 8: 1602 LCD (Guo Tianxiang)
- 成功解决TypeError: data type ‘category‘ not understood
- How to translate professional papers and write English abstracts better
- [ 英語 ] 語法重塑 之 動詞分類 —— 英語兔學習筆記(2)
- The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
- 一文读懂简单查询代价估算
- 今日夏至 Today‘s summer solstice
- Defense (greed), FBI tree (binary tree)
- CS passed (cdn+ certificate) PowerShell online detailed version
猜你喜欢
Traffic encryption of red blue confrontation (OpenSSL encrypted transmission, MSF traffic encryption, CS modifying profile for traffic encryption)
同事上了个厕所,我帮产品妹子轻松完成BI数据产品顺便得到奶茶奖励
我的创作纪念日
[web security] nodejs prototype chain pollution analysis
Facebook AI & Oxford proposed a video transformer with "track attention" to perform SOTA in video action recognition tasks
[English] Verb Classification of grammatical reconstruction -- English rabbit learning notes (2)
Market segmentation of supermarket customers based on purchase behavior data (RFM model)
Introduction and underlying analysis of regular expressions
How to convert flv file to MP4 file? A simple solution
It is necessary to understand these characteristics in translating subtitles of film and television dramas
随机推荐
论文摘要翻译,多语言纯人工翻译
What are the commonly used English words and sentences about COVID-19?
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
LeetCode每日一题(1997. First Day Where You Have Been in All the Rooms)
CS-证书指纹修改
Suspended else
[unity] how to export FBX in untiy
Simple query cost estimation
pymongo获取一列数据
Brief introduction to the curriculum differences of colleges and universities at different levels of machine human major -ros1/ros2-
Today's summer solstice
On the first day of clock in, click to open a surprise, and the switch statement is explained in detail
MySQL high frequency interview 20 questions, necessary (important)
字幕翻译中翻英一分钟多少钱?
Day 245/300 JS forEach 多层嵌套后数据无法更新到对象中
Distributed system basic (V) protocol (I)
How to translate professional papers and write English abstracts better
专业论文翻译,英文摘要如何写比较好
UniPro甘特图“初体验”:关注细节背后的多场景探索
Redis Foundation