gpt4 book ai didi

javascript - 是否可以在函数构造函数中识别哪个对象调用它,并在错误的对象调用时中止创建?

转载 作者:行者123 更新时间:2023-11-28 20:59:00 28 4
gpt4 key购买 nike

我有函数构造函数。我想控制什么函数(对象)可以调用它。示例如下:

function Bar() {

// foo can be created only here, when Bar is instantiated
var foo = new Foo();
}

function Foo() {

// I'd like to have something like this here:
if (caller != Bar) {
alert("Not allowed, the caller is not Bar");
return;
}
}

var bar = new Bar(); // this is correct, Foo can be created inside Bar
var foo = new Foo(); // prints "Not allowed, the caller is not Bar" and exits

可以用JS实现吗?有没有一些函数可以实现这种控制?

如果创建以这种方式中止,将从 Foo 创建什么?

最佳答案

您无法跨浏览器可靠地识别构造函数中的调用者,尤其是在新的严格模式下。

相反,您可以在 Bar() 内部定义 Foo() 或在同一个自执行函数内部定义它们,以便 Foo()Bar() 范围之外是未知的,因此只能在那里创建。

一些例子:

// Bar() is only known within a single scope
var Foo;
(function(){
Foo = function() {
}

function Bar() {
}
})();


// Bar() is only known inside of Foo()'s constructor
function Foo() {
function Bar() {
}
}

您可能会发现这篇文章很有指导意义,其中讨论了使实例数据真正私有(private)的各种方法:http://www.crockford.com/javascript/private.html 。它与您在这里要求的并不完全相同,但使用了一些相同的技术(在闭包中隐藏私有(private)数据)。

关于javascript - 是否可以在函数构造函数中识别哪个对象调用它,并在错误的对象调用时中止创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11512837/

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