首页 > 解决方案 > 当`let y = x`时,`y !== x`是否可能

问题描述

有没有什么情况

let x = y;
console.log(y !== x) //=> true

到目前为止,没有任何案例有效,无论是对象还是符号

?

标签: javascript

解决方案


哦,我刚发现。

使用 getter 和 setter。

如果y是全局 getter 并且每次返回不同的值,这是可能的。

// Defining y.
((i) => {
  Object.defineProperty(this, "y", {
    get: () => i++
  })
})(0)
// y is going to be one more than the previous value it gave,
// but is starts with 1.

// The magical testing...
let x = y;
console.log(x === y); // It returns `false`!
// Even y is not y.
console.log(y === y);


推荐阅读