Skip to content

Commit

Permalink
[feat] 更新 applyFn
Browse files Browse the repository at this point in the history
  • Loading branch information
maxlxq committed Aug 26, 2024
1 parent b7435d7 commit 5d0ce9f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
13 changes: 12 additions & 1 deletion code/js/apply.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
Function.prototype.applyFn = function(ctx) {
Function.prototype.applyFn = function(ctx, arr) {
if (typeof this !== 'function') {
throw new TypeError(this + ' is not a function');
}

ctx = ctx || window;
const key = Symbol();
ctx[key] = this;

const res = !arr ? ctx[key]() : ctx[key](arr);

delete ctx[key];
return res;
}
28 changes: 12 additions & 16 deletions docs/interview/js/JavaScript-apply和call.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
- call

```javascript
Function.prototype.call = function(context) {
Function.prototype.callFn = function(context) {
context = context ? Object(context) : window
var fn = Symbol()
context[fn] = this
Expand All @@ -29,22 +29,18 @@ Function.prototype.call = function(context) {
- apply

```javascript
Function.prototype.apply = function(context, arr) {
context = context ? Object(context) : window
context.fn = this

var result
if (!arr) {
result = context.fn()
} else {
var args = []
for(var i = 0, len = arr.length; i < len; i++) {
args.push(`arr[${i}]`)
}
result = eval(`context.fn(${args})`)
Function.prototype.applyFn = function(ctx, arr) {
if (typeof this !== 'function') {
throw new TypeError(this + ' is not a function');
}

delete context.fn
return result
ctx = ctx || window;
const key = Symbol();
ctx[key] = this;

const res = !arr ? ctx[key]() : ctx[key](arr);

delete ctx[key];
return res;
}
```

0 comments on commit 5d0ce9f

Please sign in to comment.