`new function()` with lower case "f" in JavaScript - javascript

My colleague has been using "new function()" with a lower case "f" to define new objects in JavaScript. It seems to work well in all major browsers and it also seems to be fairly effective at hiding private variables. Here's an example:
var someObj = new function () {
var inner = 'some value';
this.foo = 'blah';
this.get_inner = function () {
return inner;
};
this.set_inner = function (s) {
inner = s;
};
};
As soon as "this" is used, it becomes a public property of someObj. So someObj.foo, someObj.get_inner() and someObj.set_inner() are all available publicly. In addition, set_inner() and get_inner() are privileged methods, so they have access to "inner" through closures.
However, I haven't seen any reference to this technique anywhere. Even Douglas Crockford's JSLint complains about it:
weird construction. Delete 'new'
We're using this technique in production and it seems to be working well, but I'm a bit anxious about it because it's not documented anywhere. Does anyone know if this is a valid technique?

I've seen that technique before, it's valid, you are using a function expression as if it were a Constructor Function.
But IMHO, you can achieve the same with an auto-invoking function expression, I don't really see the point of using the new operator in that way:
var someObj = (function () {
var instance = {},
inner = 'some value';
instance.foo = 'blah';
instance.get_inner = function () {
return inner;
};
instance.set_inner = function (s) {
inner = s;
};
return instance;
})();
The purpose of the new operator is to create new object instances, setting up the [[Prototype]] internal property, you can see how this is made by the [Construct] internal property.
The above code will produce an equivalent result.

Your code is just similar to the less weird construct
function Foo () {
var inner = 'some value';
this.foo = 'blah';
...
};
var someObj = new Foo;

To clarify some aspects and make Douglas Crockford's JSLint not to complain about your code here are some examples of instantiation:
1. o = new Object(); // normal call of a constructor
2. o = new Object; // accepted call of a constructor
3. var someObj = new (function () {
var inner = 'some value';
this.foo = 'blah';
this.get_inner = function () {
return inner;
};
this.set_inner = function (s) {
inner = s;
};
})(); // normal call of a constructor
4. var someObj = new (function () {
var inner = 'some value';
this.foo = 'blah';
this.get_inner = function () {
return inner;
};
this.set_inner = function (s) {
inner = s;
};
}); // accepted call of a constructor
In example 3. expression in (...) as value is a function/constructor. It looks like this:
new (function (){...})(). So if we omit ending brackets as in example 2, the expression is still a valid constructor call and looks like example 4.
Douglas Crockford's JSLint "thinks" you wanted to assign the function to someObj, not its instance. And after all it's just an warning, not an error.

Related

Use string to access variable in javascript

If I have:
name.sub = function() {
var sub = {};
var placeholder = "test"
var test = function() {
return 42;
};
// Desired code would be here
return sub;
};
I want to use a placeholder to access the variable so that I get 42.
Something like
window["name"]["sub"][placeholder] is seemingly looking for name.sub.test.
The only answers I found were if it was a global variable.
Using eval would work, but I've heard it should be avoided where possible.
placeholder = "test";
console.log(eval(placeholder + '()'))
// Would return 42
My actual end goal is to have an associative array where:
console.log(array[placeholder]);
// Would return 42
Any help would be appreciated.
This is what I ended up using for anyone interested:
name.sub= function() {
var sub = {};
var placeholder = "test"
var test = function() {
return 42;
var newObj = {};
newObj["test"] = function() {test()}
console.log(newObj[placeholder]())
// Should return 42
};
You can't access variables inside a function from outside said function.
Instead, you could do this:
name.sub = function(placeholder) {
var functions = {
"test": function() {
return 42;
},
};
return functions[placeholder]();
};
name.sub("test"); // 42
I'm not sure if that's what you're looking for but hopefully it is. Explain more?
You can't access local variables inside a function the same way you can access properties of window in global scope.
kangax wrote an interesting article about Understanding delete [in JavaScript], which includes an explanation of what Activation objects are - which I think is what you're looking for.
I suggest you read the entire article, but long story short:
Inside functions, declared variables (and functions) are added as properties to the activation object of the current scope, as they get added to window in the global scope.
But unlike window:
Note that Activation object is an internal mechanism and is never really accessible by program code.
Conclusion: What you're asking is not (currently) possible.
Your options are limited to:
Using an intermediate object:
name.sub = function() {
var sub = {};
var placeholder = "test";
var array = {};
array.test = function() {
return 42;
};
console.log(array[placeholder]());
return sub;
};
Using eval, exactly like you suggested:
name.sub = function() {
var sub = {};
var placeholder = "test";
var test = function() {
return 42;
};
console.log(eval(placeholder + '()'));
return sub;
};
Using window, by removing var from test's declaration:
name.sub = function() {
var sub = {};
var placeholder = "test";
test = function() {
return 42;
};
console.log(window[placeholder]());
return sub;
};
I suggest the first option for the sake of performance over eval, for compatibility over window (might collide with other code), and simply because of personal taste and what I consider good practice.
By what i understand of your question,
its seem like you are looking for a key/value pair to a JavaScript object literal,
window.name is reserved btw: https://developer.mozilla.org/en-US/docs/Web/API/Window/name
var sub = {
'test': function() {
return 42;
},
'test2': 42;
}
sub['test']();
sub['test2'];
add by
Using dot notation:
sub.test3 = "value3";
Using square bracket notation:
sub["test4"] = "value4";
Maybe im thinking to simple , but seems like this is what you are looking for

Why does this javascript object behave differently with and without a module pattern?

I have the following code with and without a module pattern. I have given the results right next to the execution. In the module pattern, I am able to change foo and set_inner, while in the function object (non-module), I can't change foo and set_inner.
module pattern:
var someObj = (function () {
var instance = {},
inner = 'some value';
instance.foo = 'blah';
instance.get_inner = function () {
return inner; };
instance.set_inner = function (s) {
inner = s; };
return instance; })();
someObj.get_inner();//some value
someObj.set_inner("kkkk");
someObj.get_inner();//kkk
someObj.foo;//blah
someObj.foo="ddd";
someObj.foo;//ddd
non-module:
var someObj = function () {
var instance = {},
inner = 'some value';
instance.foo = 'blah';
instance.get_inner = function () {
return inner; };
instance.set_inner = function (s) {
inner = s; };
return instance; };
someObj().get_inner();//some value
someObj().foo;//blah
someObj.foo="aaa";
someObj().foo;//blah
someObj().set_inner("kkk");
someObj().get_inner();//some value
Any help is much appreciated. Thanks!
Your "module" example creates a single object, referred to by instance. The anonymous function is immediately invoked, and returns that object. So someObj refers to instance.
Your "non-module" example creates a new object each time you invoke it. The anonymous function is not immediately invoked. Instead, it has to be called every time you want to use it.
It would behave the same way if you assigned the return value to a variable and referred to that, instead of repeatedly invoking someObj:
var obj = someObj();
obj.get_inner(); //some value
obj.foo; //blah
obj.foo="aaa";
obj.foo; //aaa
//etc...

Differences in javascript module pattern

Very simple question, not sure if there are any differences in these ways of creating a javascript "module". I'm hoping somebody can clarify it for me.
A)
var foo = function() {
var bar = function() {
console.log('test');
};
return {
bar: bar
};
};
B)
var foo = function() {
function bar() {
console.log('test');
};
return {
bar: bar
};
};
C)
var foo = function() {
this.bar = function() {
console.log('test');
};
return {
bar: this.bar
};
};
A and B are essentially the same, though there is a very minor difference between A and B due to function/variable hoisting, theoretically you could write code which would work in B but break in A, but practically speaking you'd have to really write weird code to do so.
C will work, but is conceptually wrong. The point of using this.funcName in a function is as a constructor (creating lots of objects using new Thing(). If you aren't using the function as a constructor you shouldn't be using that style as someone scanning the code may mistake the function as a constructor instead of its actual purpose which is a module.
At first, you forgot to execute the function expression: the module pattern is an IEFE. You just create a function.
Your last example is nonsense, it looks like a constructor function when assigning properties to this - and when executed as a IEFE it breaks (and using it with new has undesired effects; an when returning an object it's useless).
For the difference between the first and the second snippet see var functionName = function() {} vs function functionName() {}. In context of the module pattern, the function declaration is recommended.
//Javascript Module Pattern
var person = (function() {
var cname = 'CheapFlight';
return {
name: "Santosh Thakur",
getAge: function() {
return cname;
},
growOlder: function() {
return cname + " Updated";
}
};
}());
person.cname = "New Company"
console.log(person.cname);
console.log(person.name);
console.log(person.getAge());
console.log(person.growOlder());
prefix var before a function makes it a "class"-ish, this means you can make many versions of it. This goes for A
For example:
var hi = function()
{
var bye = function()
{
alert("bye");
}
bye(); // this will call bye
var something = new bye(); // this will create a new instance of bye();
}
var something = new hi();
something();
B means you can only call bar, not make a new instance of it inside the function.
C is the same as bar because of its scope
Class-ish:
var Dog = function( hair, type )
{
this.hair = hair;
this.type = type;
}
var fred = new Dog( "long", "Dalmation" );
alert( fred.hair );
var dave = new Dog( "short", "Poodle" );
alert( dave.type);
This is a class ^

Access a function's property inside the function

I want to be able to assign a property to a function inside the function itself. I do not want to assign it to the object of invocation. So I want the equivalent of doing this:
var test = function() {
return true;
};
test.a = 'property on a function';
alert(test.a);
Instead of this, where the property is assigned to a global object:
var testAgain = function() {
this.a = "this property won't be assigned to the function";
return true;
};
testAgain();
alert(window.a);
Edit: To clarify, I'm wondering if there's something like this:
var test = function() {
function.a = 'property on a function';
};
alert(test.a); // returns 'property on a function'
Without knowing that the function is called test or having to execute it.
I know of course this isn't valid syntax
[is there a way to set a property on a function] without knowing that the function is called test or having to execute it.
Emphasis mine.
You can set a property on a function without knowing what its global variable name is necessarily going to be, however you do have to have a reference to the function in one way or another.
The module pattern is as close of a fit as I can think of:
window.test = (function () {
//the function could be named anything...
function testFn() {
...code here...
}
//...so long as the same name is used here
testFn.foo = 'bar';
return testFn;
}());
window.test.foo; //'bar'
The outer closure prevents testFn from being accessed anywhere globally, so all other references will have to use window.test.
This part of the answer is associated with the prior version of the question.
The simplest way of doing this is to use a named function:
var test = function testFn() {
testFn.foo = 'bar';
return true;
};
test.foo; //undefined
test();
test.foo; //'bar'
A better way of doing this is to use the module pattern so that you don't accidentally create issues with global leakage:
var test = (function () {
function ret() {
ret.foo = 'bar';
return true;
}
return ret;
}());
test.foo; //undefined
test();
test.foo; //'bar'
var testAgain = function() {
arguments.callee.a = "this property won't be assigned to the function";
return true;
};
testAgain();
alert(testAgain.a);​
You can do this by simple using the name to assign the property like this:
var test = function () {
test.a = 'a';
return true;
};
When test is invoked, the property will be set.
Demo
You could use arguments.callee, as su- said, but that's considered really bad practice. Also, it won't work in strict mode.
var test = function() {
test.a = 'a';
};
Or you can use prototypes, read more here.

What is the difference between the two OO methodologies in javascript?

I've been using the below, I've seen other code using function() { } and then using the this keyword, what is the difference here, have I actually instantiated an object below?
var MyObj = {
propertyOne: 'a',
Method: (function() {
function MyFuncOne() {}
function MyFuncTwo() {}
return {
MyFuncOne: MyFuncOne,
MyFuncTwo: MyFuncTwo
}
})()
}
Yes, you've instantiated a "singleton" object with two methods.
I believe the outer curly braces are unnecessary, and you could just write:
var MyObj =
(function() {
function MyFuncOne() {}
function MyFuncTwo() {}
return {
MyFuncOne: MyFuncOne,
MyFuncTwo: MyFuncTwo
};
})();
Another way to do it is:
var MyObj =
(function() {
var obj = {};
obj.MyFuncOne = function() {};
obj.MyFuncTwo = function() {};
return obj;
})();
Wrapping your JS in (function() { /* code here */ })() is good practice for preventing variables leaking into global scope. In this case, you're using it to assemble an object.
The only reason I can think of for doing something like this is if you wanted to have some private variables that were shared between the two functions (after changing it to make it legal javascript):
var MyObj = (function() {
var x,y,z; // these will be accessible only to
// the MyFuncOne and MyFuncTwo functions
function MyFuncOneA() {}
function MyFuncTwoA() {}
return {
MyFuncOne: MyFuncOneA,
MyFuncTwo: MyFuncTwoA
}
})();
I had to change your syntax to even make it work because as you had it myObj = {{...}} which isn't very useful and may have not even been valid.
Other than this private, but shared variables notion, it's just extra (and confusing) syntax for declaring two methods on an object which there are much clearer ways to do.
If you weren't using the private variables, then the above example is functionally the same as this much simpler syntax which makes a lot more sense to me:
var MyObj = {
MyFuncOne: function() {},
MyFuncTwo: function() {}
};
Using a function with the this keyword allows you to do some more things than are possible (or, at least, easy) with an object literal (which is what your anonymous function above returns). Most commonly, creating "types".
function Animal () { }
Animal.prototype.speak = function () {
return "";
};
var dog = new Animal();
dog instanceof Animal; // returns true
This also makes inheritance easier:
function Feline () { }
Feline.prototype = new Animal;
Feline.prototype.speak = function () {
return "meow";
};
function Lion () { }
Lion.prototype = new Feline;
Lion.prototype.speak = function () {
return "roar";
};
function Cat () { }
Cat.prototype = new Feline;
var leo = new Lion();
var baxter = new Cat();
leo.speak(); // returns "roar"
baxter.speak(); // returns "meow" - from prototype chain
leo instanceof Feline; // returns true
leo instanceof Animal; // returns true
leo instanceof Cat; // returns false
Demo: http://jsfiddle.net/hEnJf/

Categories