2017-06-01 179 views
2

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

我的问题是,我可以在构造函数中构造函数内的构造函数?例如:是否有可能将构造函数放在另一个构造函数的构造函数中?

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中(如
if (5 in [5, 2, 3]): ... # returns true)复制“在”关键字,使其更容易(for (var i = 0; etc.))在JavaScript中做。在这种情况下,我想要做类似foo.v("h").$in.v2("hello world")的返回true。感谢所有帮助]

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

+0

*构造器,开始* ...对不起,我不得不说。 – davcs86

+0

我不确定你想要达到什么目的。 '[5,2,3] .indexOf(5)'和'“hello world”.indexOf(“h”)'工作得很好。你可以这样做'foo.bar(var1).def'工作;有几种方法可以做到,但没有关于你想要什么的想法,很难说如何去做。 – Halcyon

+0

@Halcyon,我想要一些让它看起来更像Python的东西,比如“in”。我试图找到一种方法,使内部构造内的另一个构造函数的构造函数,这意味着像'的document.getElementById(“”)。innerHTML.'文件的主要构造,的getElementById(“”)是构造函数而innerHTML是getElementById的构造函数。 – Christian

回答

1

我想做一些像foo.v("h").$in.v2("hello world")返回[原文]真

既然你不想打电话给foo作为构造做(有在你的例子没有new),你不希望foo成为构造函数。只要有它与用v2属性返回函数(函数)v属性是指一个函数,反过来,将被赋予给它的值,并返回一个$in属性(也可能是其他人)的对象返回一个对象计算结果。

例如,下面这些都是同一个对象,但你可能会使用不同的对象的不同状态;看评论:

// 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"));

-2

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

+0

我已经添加了一个返回值,但是我忘了将它添加到示例代码中。它不起作用。 – Christian

+0

你添加的返回值是什么?它有'def'属性吗? – Kermit

+1

这不回答这个问题 – niceman

相关问题