繁体   English   中英

是否可以将构造函数放在另一个构造函数的内部?

[英]Is it possible to put a constructor function inside a constructor function inside another constructor?

我正在制作一个项目,可以在Python中添加Python 3功能。 例如,“中”。

我的问题是,我可以在构造函数内的构造函数内创建一个构造函数吗? 例如:

var foo = new function foo() {
    this.bar = function(Variable1) {
        this.def = function() {
            // code
        }
        return ""; // to prevent error with undefined
    }

foo和foo.bar(var1)有效,但是foo.bar(var1).def不起作用。 我搞砸了,试图做foo.def,它起作用了。 我糊涂了; 为什么foo.def工作,而foo.bar(var1).def不能工作?

[我为什么要考虑这样做? 我想从Python 3复制“ in”关键字(例如
if (5 in [5, 2, 3]): ... # returns true ),以使其更容易( for (var i = 0; etc.) )在JavaScript中执行。 在那种情况下,我想做类似foo.v("h").$in.v2("hello world")返回true的操作。 感谢您提供的所有帮助!]

编辑:感谢所有评论者的所有帮助。 ;)

我想做类似foo.v("h").$in.v2("hello world")返回[sic] true

由于您不想将foo称为构造函数(示例中没有new ),因此您不希望foo成为构造函数。 只是让它返回一个带有v属性的对象,该对象引用一个函数,该函数依次存储赋予它的值并返回一个带有$in属性的对象(可能还有其他对象),该对象返回一个带有v2的函数(函数)计算结果的属性。

例如,这里的所有对象都是相同的,但是您可以将不同的对象用于不同的状态。 看评论:

 // The operations we allow, including how many operands they expect var operations = { // We'll just do $in for now $in: { operandCount: 2, exec: function(operands) { return String(operands[1]).indexOf(String(operands[0])) != -1; } } }; // Prototype of objects returned by `foo` var proto = { // `v` sets the next operand; if we have an operation and we have enough // operands, it executes the operation; if not, returns `this` for chaining v(operand) { if (!this.operands) { this.operands = []; } this.operands.push(operand); if (this.operation && this.operation.operandCount == this.operands.length) { return this.operation.exec(this.operands); } return this; }, // `$in` is defined as a property with a getter to satisfy your syntax. // In general, getters with side-effects (like this one) are a Bad Thing™, // but there can be exceptions... Returns `this` because `$in` is an infix // operator. get $in() { if (this.hasOwnProperty("operation")) { throw new Error("Cannot specify multiple operations"); } this.operation = operations.$in; return this; } }; // `foo` just creates the relevant object function foo() { return Object.create(proto); } // Examples: console.log("Should be true:", foo().v("h").$in.v("hello world")); console.log("Should be false:", foo().v("h").$in.v("nope, don't 'ave it")); 

foo.bar(var1)被调用,结果应该是功能栏的返回值。功能栏没有返回值,因此foo.bar(var1).def不起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM