8
头图

Preface

Hello everyone, I’m Lin Sanxin. me the most difficult knowledge points in the most easy-to-understand terms. 161a6d02207fff is my motto, and is the prerequisite for is my original intention. Today I will tell you a question, which is an interview question for Netease.

  • A student: "How to implement JS overloading?"
  • Me: "Does JS have overloads? Isn't it only for TS?"
  • A classmate: "Yes, this is an interview question for Netease"
  • Me: "Okay, I think about it!"

image.png

What is overloading

The first time I saw the word overload Java before. I always felt that JavaScript had no overloads until TypeScript appeared, so I always felt that JavaScript did not have overloads, and TypeScript only has it, but now I see it. I was wrong to come.

The overload I understand is: the same function, different number of parameters, execute different codes, such as:

/*
* 重载
*/
function fn(name) {
  console.log(`我是${name}`)
}

function fn(name, age) {
  console.log(`我是${name},今年${age}岁`)
}

function fn(name, age, sport) {
  console.log(`我是${name},今年${age}岁,喜欢运动是${sport}`)
}

/*
* 理想结果
*/
fn('林三心') // 我是林三心
fn('林三心', 18) // 我是林三心,今年18岁
fn('林三心', 18, '打篮球') // 我是林三心,今年18岁,喜欢运动是打篮球

But it is definitely not possible to write it directly in JavaScript . Let’s take a look at the actual execution result of the above code. You can see that the last fn covers both of the first two, so the overload is not implemented. Effect

我是林三心,今年undefined岁,喜欢运动是undefined
我是林三心,今年18岁,喜欢运动是undefined
我是林三心,今年18岁,喜欢运动是打篮球

My approach

In fact, if I want to achieve the ideal overload effect, I still have a way. I can just write a fn function, and judge arguments type array in this function, and execute different codes to complete the overload. Effect

function fn() {
  switch (arguments.length) {
    case 1:
      var [name] = arguments
      console.log(`我是${name}`)
      break;
    case 2:
      var [name, age] = arguments
      console.log(`我是${name},今年${age}岁`)
      break;
    case 3:
      var [name, age, sport] = arguments
      console.log(`我是${name},今年${age}岁,喜欢运动是${sport}`)
      break;
  }
}

/*
* 实现效果
*/
fn('林三心') // 我是林三心
fn('林三心', 18) // 我是林三心,今年18岁
fn('林三心', 18, '打篮球') // 我是林三心,今年18岁,喜欢运动是打篮球

But the student said that the interviewer of Netease seemed to think that this could be achieved, but if there is a better way to achieve it, I was confused.

High-end practices

image.png

After searching for information on the Internet, I found a relatively high-end approach. You can use the closure to achieve the effect of overload. This method is in the "secrets of the JavaScript ninja" written by John Resig, the father of JQuery. This method makes full use of the closure feature

function addMethod(object, name, fn) {
  var old = object[name]; //把前一次添加的方法存在一个临时变量old里面
  object[name] = function () { // 重写了object[name]的方法
    // 如果调用object[name]方法时,传入的参数个数跟预期的一致,则直接调用
    if (fn.length === arguments.length) {
      return fn.apply(this, arguments);
      // 否则,判断old是否是函数,如果是,就调用old
    } else if (typeof old === "function") {
      return old.apply(this, arguments);
    }
  }
}

addMethod(window, 'fn', (name) => console.log(`我是${name}`))
addMethod(window, 'fn', (name, age) => console.log(`我是${name},今年${age}岁`))
addMethod(window, 'fn', (name, age, sport) => console.log(`我是${name},今年${age}岁,喜欢运动是${sport}`))

/*
* 实现效果
*/

window.fn('林三心') // 我是林三心
window.fn('林三心', 18) // 我是林三心,今年18岁
window.fn('林三心', 18, '打篮球') // 我是林三心,今年18岁,喜欢运动是打篮球

Concluding remarks

If you think this article is of little help to you, please give me a thumbs up and encourage Lin Sanxin haha. Or you can join my fish-fishing group. Let's study hard together, ah ah ah ah ah, I will mock interviews regularly, resume guidance, answer questions and answer questions, let's learn from each other and make progress together! !
截屏2021-11-28 上午9.43.19.png

Reference


Sunshine_Lin
2.1k 声望7.1k 粉丝