gpt4 book ai didi

javascript - 保护构造函数以防止丢失 'new' 是一种好习惯吗?

转载 作者:数据小太阳 更新时间:2023-10-29 05:53:01 26 4
gpt4 key购买 nike

From Secrets of the Javascript Ninja (很棒的演练顺便说一句):

// We need to make sure that the new operator is always used
function User(first, last){
if ( !(this instanceof User) )
return new User(first, last);

this.name = first + " " + last;
}

var name = "Resig";
var user = User("John", name);

assert( user, "This was defined correctly, even if it was by mistake." );
assert( name == "Resig", "The right name was maintained." );

是否有任何真实世界的代码风格指南让所有构造函数都执行这种保护(前两行)?我相信 linters 会捕获像 User("John", "Resig") 这样的调用并警告丢失的 new,不是吗?

最佳答案

我建议你使用严格模式,并在支持它的浏览器中进行测试。例如,

function User(first, last) {
"use strict";
this.name = first + " " + last;
}

如果您忽略 new,这将进入严格模式。例如,

User("a", "b")

将在 Firefox 中抛出一个 TypeError。这使您可以捕获错误,而不必支付 instanceof 检查的代价。即使您在严格模式之外调用它,它也会抛出类型错误。这是因为直接调用的严格模式函数将 this 绑定(bind)到 undefined 而不是全局。在 undefined 上设置属性会导致 TypeError 异常。

关于javascript - 保护构造函数以防止丢失 'new' 是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9645155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com