I am making a project where Python 3 features can be added into JavaScript. For example, "in".
My question is, can I make a constructor function inside a constructor function inside a constructor? For example:
var foo = new function foo() {
this.bar = function(Variable1) {
this.def = function() {
// code
}
return ""; // to prevent error with undefined
}
foo and foo.bar(var1) works, but foo.bar(var1).def doesn't. I messed with it and tried to do foo.def, and it worked. I'm confused; why does foo.def
work, but not foo.bar(var1).def
?
[Why am I thinking of doing this? I want to replicate the "in" keyword from Python 3 (like if (5 in [5, 2, 3]): ... # returns true
) to make it easier (for (var i = 0; etc.)
) to do in JavaScript. In that case, I wanted to do something like foo.v("h").$in.v2("hello world")
returns true. Thanks for all the help!]
EDIT: Thanks for all the help from all the commenters. ;)
I wanted to do something like
foo.v("h").$in.v2("hello world")
returns [sic] true
Since you don't want to call foo
as a constructor (there's no new
in your example), you don't want foo
to be a constructor. Just have it return an object with a v
property which refers to a function that, in turn, stores the value given to it and returns an object with an $in
property (and probably others) which returns a function (functions) with a v2
property that calculates the result.
For example, here those are all the same object, but you may well use different objects for different states; see comments:
// 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"));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments