前端JS面试题

题目:

实现函数计算   Cal(2).加(1).减(2).乘(3).除(3),Cal函数只是一个传参函数

分析:在此题中每次函数调用结束会调用下一个函数,即函数返回值是一个对象,这是我们可以考虑使用原型链和this

function Cal(num) {
  let obj = {
    num
  }
  Object.defineProperties(obj.__proto__, {
    add: {
      value: function(n) {
        this.num += n
        return this
      }
    },
    jian: {
      value: function(n) {
        this.num -= n
        return this
      }
    },
    cheng: {
      value: function(n) {
        this.num *= n
        return this
      }
    },
    chu: {
      value: function(n) {
        this.num /= n
        return this
      }
    }
  })
  return obj
}
let obj = Cal(2)
  .add(1)
  .jian(2)
  .cheng(3)
  .chu(3)
console.log(obj.num) //1

猜你喜欢

转载自blog.csdn.net/ll18781132750/article/details/81103025