js在构造函数里面原型重写

JavaScript021

js在构造函数里面原型重写,第1张

js在构造函数里面原型重写就是prototype.xxx,xxx是用户自定义的函数名。

比如定义一个add方法,写法如下:

Number.prototype.add = function(num){return(this+num)}

prototype 是在 IE 4 及其以后版本引入的一个针对于某一类的对象的方法,当你用prototype编写一个类后,如果new一个新的对象,浏览器会自动把prototype中的内容替你附加在对象上。这样,通过利用prototype就可以在JavaScript中实现成员函数的定义,甚至是“继承”的效果。

// 重写toFixed方法

Number.prototype.toFixed = function (n) {

  if (n >20 || n <0) {

      throw new RangeError('toFixed() digits argument must be between 0 and 20')

  }

  const number = this

  if (isNaN(number) || number >= Math.pow(10, 21)) {

      return number.toString()

  }

  if (typeof (n) == 'undefined' || n == 0) {

      return (Math.round(number)).toString()

  }

  let result = number.toString()

  const arr = result.split('.')

  // 整数的情况

  if (arr.length <2) {

      result += '.'

      for (let i = 0i <ni += 1) {

          result += '0'

      }

      return result

  }

  const integer = arr[0]

  const decimal = arr[1]

  if (decimal.length == n) {

      return result

  }

  if (decimal.length <n) {

      for (let i = 0i <n - decimal.lengthi += 1) {

          result += '0'

      }

      return result

  }

  result = integer + '.' + decimal.substr(0, n)

  const last = decimal.substr(n, 1)

  // 四舍五入,转换为整数再处理,避免浮点数精度的损失  正数+1 负数-1

  if (parseInt(last, 10) >= 5) {

      const x = Math.pow(10, n)

      result = (Math.round((parseFloat(result) * x)) + (parseFloat(result) >0 ? 1 : -1)) / x

      result = result.toFixed(n)

  }

  return result

}

现在写一个函数,这个函数的返回值是一个对象,来观察一下这个对象,和函数体内this指向

①,对象a就是一个空对象

②,对象a没有color属性

③,对象a原型指向Object.prototype

④,函数体内this指向window(上图可见,没调用函数之前,window.color属性不存在)

在执行函数时,加一个new试试看有啥效果:

①,没有return,这个函数居然返回了一个对象

②,对象a有个color属性

③,对象a的原型指向了这个构造函数的prototype属性

④,window对象没有color属性

⑤,this指向了对象a

由上得出总结new的作用:

①,new能让一个构造函数返回一个对象(下面称为A)而无需return

②,new会让函数体内的this指向这个A

③,new会让A的原型指向这个构造函数的prototype属性

PS:

①,new只用了三个字符,却实现了很多功能,非常贴心,可以称呼new为语法糖或贴心语法( syntactic sugar )

②,一个函数自带prototype对象,而且里面默认有一个constructor属性,这个属性返回实例对象的构造函数,如果你重新给prototype对象赋值,小心不要覆盖掉它

③,如果使用new,函数内就别 return一个对象 了 ,这样返回的是return后面的对象,this不会指向它

④,就算函数体内空空如也,new的作用不变