new 操作符都做了什么

解答

stackoverflow 原提问,https://stackoverflow.com/questions/9468055/what-does-new-in-javascript-do-anyway

new f(a, b, c)

is eaqal to

// Create a new instance using f's prototype.
var newInstance = Object.create(f.prototype), result;

// Call the function
result = f.call(newInstance, a, b, c);

// If the result is a non-null object, use it, otherwise use the new instance.
result && typeof result === 'object' ? result : newInstance;

testing

var f = function () {
    this.test = 1;
}

var newInstance = Object.create(f.prototype), result;

result = f.call(newInstance);

console.log(result, '--', newInstance);
// undefined -- f {test: 1}
var f = function () {
    this.test = 1;
    return this;
}

var newInstance = Object.create(f.prototype), result;

result = f.call(newInstance);

console.log(result, '--', newInstance);
// f {test: 1} -- f {test: 1}

疑问:'1'.toString()为什么可以调用?

其实在这个语句运行的过程中做了这样几件事情:

var s = new Object('1');
s.toString();
s = null;
  • 第一步: 创建Object类实例。注意为什么不是String ? 由于Symbol和BigInt的出现,对它们调用new都会报错,目前ES6规范也不建议用new来创建基本类型的包装类。
  • 第二步: 调用实例方法。
  • 第三步: 执行完方法立即销毁这个实例。

整个过程体现了基本包装类型的性质,而基本包装类型恰恰属于基本数据类型,包括 Boolean, Number 和 String。

那为什么 1.toString() 报错?

> 1.toString()
VM416:1 Uncaught SyntaxError: Invalid or unexpected token

这是因为 JavaScript 的解释器会把数字后的"."当作小数的点,引发了语法错误。

猜你喜欢

转载自www.cnblogs.com/everlose/p/12501285.html