是否有可能将构造函数放在另一个构造函数的构造函数中?
问题描述:
我正在制作一个项目,可以将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。感谢所有帮助]
编辑:感谢所有的评论者所有帮助。 ;)
答
我想做一些像
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"));
*构造器,开始* ...对不起,我不得不说。 – davcs86
我不确定你想要达到什么目的。 '[5,2,3] .indexOf(5)'和'“hello world”.indexOf(“h”)'工作得很好。你可以这样做'foo.bar(var1).def'工作;有几种方法可以做到,但没有关于你想要什么的想法,很难说如何去做。 – Halcyon
@Halcyon,我想要一些让它看起来更像Python的东西,比如“in”。我试图找到一种方法,使内部构造内的另一个构造函数的构造函数,这意味着像'的document.getElementById(“”)。innerHTML.'文件的主要构造,的getElementById(“”)是构造函数而innerHTML是getElementById的构造函数。 – Christian