-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
47 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,28 @@ | ||
Function.prototype.myApply = function(context, arr) { | ||
function copySymbol(obj) { | ||
const unique_proper = "00" + Math.random(); | ||
if (obj.hasOwnProperty(unique_proper)) { | ||
arguments.callee(obj)//如果obj已经有了这个属性,递归调用,直到没有这个属性 | ||
} else { | ||
return unique_proper; | ||
} | ||
} | ||
const isArray = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLocaleLowerCase() === 'array' | ||
Function.prototype.myApply = function (context, arr) { | ||
if(typeof this !== 'function') { | ||
return 'err' | ||
} | ||
context = context || window | ||
context.fn = this | ||
const fnName = copySymbol(context) | ||
context[fnName] = this | ||
let res | ||
if(!arr) { | ||
res = context.fn() | ||
if (arr) { | ||
if (!isArray(arr)) { | ||
throw '第二个参数必须是数组' | ||
} | ||
res = context[fnName](...arr) //如果有返回值 | ||
} else { | ||
res = context[fnName]() | ||
} | ||
res = context.fn(...arr) //如果有返回值 | ||
delete context.fn | ||
delete context[fnName] | ||
return res | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters