gpt4 book ai didi

javascript - 将调用者的引用添加到闭包构造函数中

转载 作者:行者123 更新时间:2023-11-28 02:36:28 25 4
gpt4 key购买 nike

好吧,我正在闭包中为另一个函数创建一个构造函数对象(以将其隐藏起来,使其免受可能与其冲突的其他脚本的影响)(这一点稍后会变得清楚)。有没有办法将调用者函数的引用添加到封闭的构造函数中:

// this can be located anywhere within a script
(function() {
function SomeConstructor(param) { this.param = param; }
SomeConstructor.prototype.doSomething = function(a) { this.param = a; return this; }
SomeConstructor.prototype.getParam = function() { return this.param }
// SomeConstructor.prototype.someFunct = ???

return function someFunct(param) {
if (param instanceof SomeConstructor) {
return param;
}
else if (param) {
return new SomeConstructor(param);
}
}
}());

我需要引用的原因是这样我可以在 someFunct 和它的构造对象之间进行链接:

someFunct("A").doSomething("a").someFunct("B").doSomething("a").getParam();



请注意,我需要保留 instanceof 检查,以便指定以下功能:

// 1: The inner call creates a new instance of SomeConstructor
// 2: The 2nd(wrapping) call returns the inner calls instance
// instead of creating a new isntance
var a = someFunct(someFunct("b"));

最佳答案

先将函数赋值给原型(prototype)的属性,然后返回该属性:

(function() {
function SomeConstructor(param) { this.param = param; }
SomeConstructor.prototype.doSomething = function(a) { this.param = a; return this; }
SomeConstructor.prototype.getParam = function() { return this.param }
SomeConstructor.prototype.someFunct = function someFunct(param) {
if (param) {
return new SomeConstructor(param);
}
}

return SomeConstructor.prototype.someFunct;
}());

关于javascript - 将调用者的引用添加到闭包构造函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13413510/

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