使用窗口作为原型在javascript中返回看似错误的值 [英] using window as a prototype returns seemingly wrong values in javascript

查看:54
本文介绍了使用窗口作为原型在javascript中返回看似错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你希望这段代码返回123,而是返回窗口对象

you'd expect this code to return "123", but instead it returns the window object

function W() {
    this.window = "123";
}

W.prototype = window;

(new W()).window; // window object, not "123"

请检查后续问题(窗口原型使setTimeout表现得很奇怪

推荐答案

正如已经指出的那样 window.window 是不可变的,但你可以定义自己的窗口 中的属性W()构造函数。

As it was already pointed out window.window is immutable, but you can define own window property in W() constructor function.

function W() {
  Object.defineProperty(this, 'window', {
    configurable: true,
    enumerable: true,
    writable: true,
    value: '123'
  });
}

W.prototype = window;
document.write(new W().window); //123

这篇关于使用窗口作为原型在javascript中返回看似错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆