Jquery name space functional process is not understandable - javascript

I searching across the web about the jquery.namespace process. finally i got a answer in the stack overflow with this example script..
jQuery.namespace = function() {
var a=arguments, o=null, i, j, d;
for (i=0; i<a.length; i=i+1) {
d=a[i].split(".");
o=window;
for (j=0; j<d.length; j=j+1) {
o[d[j]]=o[d[j]] || {};
o=o[d[j]];
console.log(o);
}
}
// console.log(o); //Object {}
return o;
};
// definition
jQuery.namespace( 'jQuery.debug' );
jQuery.debug.test1 = function()
{
alert( 'test1 function' );
};
jQuery.debug.test2 = function()
{
alert( 'test2 function' );
};
// usage
jQuery.debug.test1();
jQuery.debug.test2();
It has 2 parts, once is "Jquery.namespace" - function and another is declaring new methods to name space. But i unable to understand what is "Jquery.namespace" function exactly do here.. i tried to understand line by line, but i couldn't get the process what the function do here..
Any one explain me about the function, about how that's works? or any other easy method to make name spacing using jQuery..
Thanks in advance

The function is taking arguments which are a list of namespaces you want created.
lets simplify it so it only takes one namespace
jQuery.namespace = function(namespace) {
var o=null, j, d;
d=namespace.split(".");
o=window;
for (j=0; j<d.length; j=j+1) {
o[d[j]]=o[d[j]] || {};
o=o[d[j]];
}
}
return o;
};
The function is then fairly simple. What is actually happening is starting from the window we are recursively checking if the objects we have declared in our namespace exist. For example take the call jQuery.namespace('foo.bar') the function would check to see if the window had an attribute foo and if not it would create it. The function would then check if window.foo had an attribute bar and if not create it.
In the end all the function does is create an object linked to the window (a global variable) which has all the relevant sub-objects. You are then just assigning functions and variables to the nested object rather than directly to the window which you would otherwise do with global variables.

Related

Javascript OOP and Classes Problems

I wanted to rearrange my Code to OOP, but I am not able to figure out my errors here, especially since they appear correct according to different Tutorials and examples.
I suppose I misunderstand something of JS´s, object-instantiation and Call stack.
I will provide some examples, which I don´t understand.
What I want here is to do some operations on an Array and then get it to an other class.
https://jsfiddle.net/8g22nj8y/1/
<script>
$(document).ready(function() {
var p = new Parser();
p.init();
p.getArray();
p.getArray2();
p.get3();
}</script>
function Parser() {
var myArray = [];
this.myArray2 = [];
thisReference = this;
this.myArray3=[];
return {
init: function () {
alert("huhu");
this.parse2();
parse();
},
getArray: function () {
alert(thisReference.myArray2.length);
},
getArray2: function () {
alert(myArray);
}
}
function parse() {
var arr = [1, 2, 3];
myArray.push(arr);
myArray2.push(arr);
for(var i =0;i<10;i++){
a=[];
a.push(i);
thisReference.myArray3.push(a);
}
}}Parser.prototype.parse2 = function () {
var arr = [1, 2, 3];
myArray.push(arr);
this.myArray2.push(arr);};
Independent how I run it, it always says that this.parse2() is not a function.
When I am only using parse(), it says that myArray2 is undefined, althought it´s clearly there - just as "class variable". If I change myArray2 in parse() to thisReference.myArray2 it´s working.
Why? I thought an inner Function - which parse() clearly is, is able to grab all the variable in the outer function - in this case Parser(). When I am now using myArray3 either if it´s used with thisReference or with this. "it is not defined".
If I call parse2 with thisReference it´s working, but then "myArray is not defined", yes it´s an local variable but it´s in the same class and if I call parse() I am able to use it without problems.
Furthermore:
simplified: https://jsfiddle.net/Lzaudhxw/1/
function Syntax(){
var mine = new Lex();
myRef=this;
}
Class1.prototype.foo=function(){
myRef.mine.setFunc(5);
myRef.mine.publicFunc();}
function Lex(){
this.x, this.h=1;
return{
publicFunc: function(param){
this.h;
this.x;
},
setFunc: function(x){
this.x=x;
}
}
Initially I set h to be 1. If I now instantiiate Syntax and call from that the publicFunc from Lex both are undefined. But if I run foo() from Syntax and call the publicFunc again, x is set to the value and h is undefined. Why is it not possible to predefine an varriable (in this case h) like that and then use it?
EDIT to Jan´s Answer:
I read in many Tutorials and some production code that you should store "this" into an variable. Why should myRef point to anything else than the Syntax Object? :O
Why is myRef not an variable of Syntax? Does it have to be this.myRef?
Ahh right, var means local, so mine is only accessiable in the constructor?!
I didn´t wanted to init "x", only define it.
Ahh with return{} I am creating a new class/object, then it´s clear that this. does not point to the above vars. But to introduce an myRef=this should do the job, right?
...So, it´s wiser to use prototype to add functions instead of an inner function?
Yeah you've got a bunchload of JS concepts wrong. I suggest you read the documentation. Tried adding a few explanations.
function Syntax(){
// Since you're returning a new object from "Lex" straight away, there's
// little point of using "new" here
var mine = new Lex();
// Why store "this" here? "this" will be accessible from your prototype
// methods pointing to your object instance... Provided you use "new Syntax()",
// Otherwise "myRef" will (probably) point to the global object.
myRef=this;
}
// Where's "Class1"? You don't have a Class1 function anywhere. You probably mean "Syntax"
Class1.prototype.foo=function() {
// "myRef" is not a property of "Syntax", so it wouldn't be accessible here.
// Furthermore, "mine" is declared as a variable above, so it wouldn't be
// accessible in this manner even if "myRef" pointed to "this" (which it doesn't).
myRef.mine.setFunc(5);
myRef.mine.publicFunc();
}
function Lex(){
// This is a correct property declaration of h. You're not setting the
// value of x here though, just calling it. Javascript allows "trying"
// to call ANY property of ANY object without giving neither a compilation
// nor runtime error, so calling the undefined "this.x" here is valid.
// It just won't do anything.
this.x, this.h=1;
// Here you return a new object straight off, so the below "this" will point
// to the object below, not the "Lex" object defined above. So your above
// defined "this.h" will not be used, it's a property of a different object.
return {
publicFunc: function(param){
this.h;
this.x;
},
setFunc: function(x){
this.x=x;
}
}
// You're missing a closing bracket here.
What you're probably trying to do would look something like this with correct Javascript syntax
function Syntax(){
this.mine = Lex();
}
Syntax.prototype.foo=function() {
this.mine.setFunc(5);
this.mine.publicFunc();
}
function Lex() {
return {
h:1,
publicFunc: function(){
console.log(this.h);
console.log(this.x);
},
setFunc: function(x){
this.x=x;
}
}
}
var s = new Syntax();
s.foo();
But returning an object from Lex would be pretty impractical in most cases. So what you really REALLY want to do is probably
function Syntax(){
this.mine = new Lex();
}
Syntax.prototype.foo = function() {
this.mine.setFunc(5);
this.mine.publicFunc();
}
function Lex() {
this.h = 1;
}
Lex.prototype = {
publicFunc: function(){
console.log(this.h);
console.log(this.x);
},
setFunc: function(x){
this.x=x;
}
};
var s = new Syntax();
s.foo();

Is it possible to change scope of function after new Function()?

So I have this code:
function fn(a){
var f=(new Function("return a"));
return f();
}
fn(7)//ReferenceError: a is not defined
Same problems with local variables:
function fn(){
var a=7;
var f=new Function("return a");
return f();
}
fn(7)//ReferenceError: a is not defined
I want it to return a but the new function cant see a,
it can only see global a
var a=1;
function fn(a){
var f=(new Function("return a"));
return f();
}
fn(7)//1
With the normal initialization the function can see the argument.
function fn(a){
var f=function(){return a};
return f();
}
fn(7)//7
I need to call the basic constructor in my project and can't use global variables.
I know that i could solve this by giving arguments to the newly created function and call it with that like this:
function fn(a){
var f=(new Function('a',"return a"));
return f(a);
}
fn(7)//7
And also could use some parsing function and some stupidly long method to make incoming arguments reachable like this:
function parsargs(funct){
//some parsing methodes giving back argument name list from funct.toString()
return "['a','b']";//like this
}
function fn(a,b){
var arrgstr,retfunc;
arrgstr="";
for(var i in arguments)
{
if(i<arguments.length-1)
arrgstr+=arguments[i]+",";
else
arrgstr+=arguments[i];
}
//return arrgstr;
retfunc="var f=new Function("+parsargs()+",'return b*a');return f("+arrgstr+")";
return (new Function(retfunc))();
}
fn(7,4)//28
But there must be an easier way which reaches local variables and functions as well...
Any suggestions?
PS:
i am trying to replace eval() in the project
Here is a simplified version of my original problem:
fiddle
The answer is NO...
Your exact question isn't clear but, supposing you can use arguments.callee (i.e. non strict mode) and that you want to be able to have any arguments name in fn, you "may" do this:
function fn(a,b){
var strargs = arguments.callee.toString().match(/\(([^\)]*)\)/)[1];
return (new Function(strargs.split(","),"return a+b")).apply(null,arguments);
}
console.log(fn(7, 3)) // 10
But I have a strong feeling this is a XY question and that we could have given a more useful answer knowing the real original problem to solve.
You could call your new Function with a context that references the local variables that you need:
function f(a) {
var b = 30;
return new Function("return this.a + this.b").call({ a: a, b: b })
}
f(10) // 40
The reason why this isn't working as easy as you would like is that JavaScript doesn't blindly put variables in a scope. Instead, it parses the function body (as good as it can) and determines which variables the code will need. It will then look up the variables in the outer scopes, create references for them and attach those references to the new function. That's what keeps variables from the outer scope accessible inside of the function when it eventually will be executed.
You want to build a function from a string body. JavaScript can't tell which variables the body will use and hence, it won't make those variables available.
To make it work for function arguments, use apply()::
function fn(a){
var argref = arguments; // create reference to the arguments of fn() and hence to a or any other arguments
var func = new Function("return arguments[0]");
var wrapper = function() {
return func.apply(null, argref);
};
return wrapper;
}
Note that you still can't reference arguments by name since the code never specifies what the names of the arguments of func are - JavaScript can't magically read you mind and do what you want. If you want to access the arguments by name, you need to tell the interpreter the names.
This question has some code how to determine the names from a function reference: How to get function parameter names/values dynamically from javascript
I don't see a way to make local variables available without passing them to fn() as arguments. Even if you used them inside of fn(), they would be out of scope when func() is eventually executed.
A simple solution would be to pass an object to fn():
function fn(conf) {
var func = new Function('conf', "return conf.a");
var wrapper = function(conf) {
return func.apply(null, conf);
};
return wrapper;
}
fn({a:7});
new Function doesn't create a closure context, but eval does.
Here's a low-tech way to build a function with an arbitrary evaluated body and access to the calling scope:
function f(a) {
return eval("(function() { return a })")()
}
f(10) // 10

List all defined functions name by user in V8

From 3 hours, I search for make a Javascript function who return the list of reachable/created functions by an user.
Unfortunately, I don't find anything....
You know how to do this on google V8 Javascript engine ?
PS: Sorry for my english, I'm french student :D
There is no programmatical way of scraping a list of current functions or variables.
You would in the least need to know where these functions lived - e.g. on a particular namespace.
var fn = {};
fn.someFunc = function(){}
fn.someProp = 'foo';
fn.someOtherFunc = function(){}
//get all funcs
for (var i in fn) if (typeof fn[i] == 'function') alert('found a function');
Please note that by default the functions which are not declared as a method of an object are considered as a method of window object.
So, using something like the code below you can list all functions of window object.
You can inspect the output and add better filters to improve isFunction function which I steal here.
<script type="text/javascript">
function myTest() //function to be detected
{
return true;
}
function isFunction(functionToCheck)
{
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) == '[object Function]';
}
for( var it in window )
{
if(isFunction(window[it]))
console.log(it+":"+window[it]);
}
</script>
Maybe I can help you. This call go top to down in every object, starting with global context. the first function return the global object that is where are our free-scope objects . And we do a recursion over each object search for functions or anything you want.
var global = (function(){return this;})();
(function(ctx){
for(var i in ctx) {
// put your function check here.
// System.out.println(i + ' ' + typeof ctx[i]);
if(ctx[i] instanceof Object) {
arguments.callee(ctx[i]); }
}
})(global);
run code on the fly

Javascript module pattern - losing scope of this

Been working on a js module pattern for a while to meet the escalating needs of "some website". Essentially, I just need a good way of grouping / encapsulating scripts, along with the sometime need for OO patterns.
I've got a structure that works ok, but I'm not happy with certain parts of it... so I'm in the process of refactoring it. Here is the updated pattern:
(function (global) {
var M = {
VERSION : 1.0
};
global.M = M;
//jQ document.ready()
global.onload = function(){
console.log('M VERSION: %s', M.VERSION);
var main = new M.Main();
};
M.Main = function(){
var _class1;
var _class2;
var _class3;
function _init(){
_class1 = new M.Class('foo','baz');
console.log('_class1.param2 : %s', _class1.getParam() ); //works
_class2 = new M.OtherClass('faz','boo');
_class2.setParam('Boozaz');
console.log('_class2.param2 : %s', _class2.getParam() ); //works
_class3 = new M.Class('fuz','boz')
console.log('_class3.param2 : %s', _class3.getParam() ); //works
_class3.prototype = new M.Super();
console.log('_class3.__param : %s', _class3.prototype.getProtected() ) //works
}
_init();
return true;
};
M.Super = function(){
var __param = 'jQ';
M.Super.API = {
getProtected : function(){ return __param }
}
return M.Super.API;
}
M.Class = function( p1, p2){
var _param1;
var _param2;
function _init(){
_param1 = p1;
_param2 = p2;
}
function _getParam(){
return _param2;
}
function _setParam(e){
_param2 = e;
}
M.Class.API = {
getParam : function(){ return _getParam(); },
setParam : function(e){ _setParam(e) },
publicMethod : function(){ ... }
}
publicMethod() //fails
this.publicMethod() //fails, this scopes to DOM window
M.Class.API.publicMethod() // works, but is kludgy
_init();
return M.Class.API;
};
})(typeof window === 'undefined' ? this : window);
This produces a satisfactory DOM structure (on inspection via firebug) - but I'm losing scope of this in one specific area = calling the "public" methods of the returned object, internally.
publicMethod() //fails
this.publicMethod() //fails, this scopes to DOM window
M.Class.API.publicMethod() // works, but kludgy syntax
In the previous iteration of this pattern, the "class" object is self-executing, and reference to this is maintained :
M.Class = function( p1, p2){
var _param1;
var _param2;
var _root;
function _init(){
_root = this; //this gets referenced for later usage
_param1 = p1;
_param2 = p2;
}
function _getParam(){
return _param2;
}
function _setParam(e){
_param2 = e;
}
M.Class.API = {
init : function(){ _init(); },
getParam : function(){ return _getParam(); },
setParam : function(e){ _setParam(e) },
}
console.log('getParam, internal :%s', _root.getParam() ) //success
return M.Class.API;
}();
M.Class.init();
However, in the refactored pattern, I wish instantiate these "classes" via new, to gain more control over execution order.
I've read many, many articles on the fairly mind numbing subject of lexical scope in js... yet come up with no conclusions.
How should I maintain the scope of this in my updated module pattern?
This is one of those philosophical questions that everyone asks when writing a library or module: should functions reference the container object using this or the variable name? The answer is: it depends.
If you know that the function will always be called with the correct value of this (e.g. a method on a prototype), then use this. However, if the function might be called any other way, then use the variable name. If you decide at some later stage to change the name, it's a pretty simple search and replace exercise. And calling myLib.utils.someFn is a lot clearer than calling this.someFn to me. And if you feel it's too much typing, you can always revert to var sF = myLib.utils.someFn and go from there.
Edit
To answer your questions:
publicMethod() //fails
There is no publicMethod identifier in the current scope, it will fail.
this.publicMethod() //fails, this scopes to DOM window
If the call was M.Class(), then this is a reference to M. If you are getting window, then you are calling the function some other way.
M.Class.API.publicMethod() // works, but is kludgy
Because that is how you have set it up. If you don't like it, set it up some other way.
Lastly:
)(typeof window === 'undefined' ? this : window);
seems to be one of those mystic incantations that seem to proliferate on the web. What is the purpose? If the intent is to pass a reference to the global object to the function, then:
)(this);
is sufficient everywhere. The purpose of the above is to ensure that the function has a reference to the global object because referencing window might resolve to some other object. Including logic that may or may not pass in the global object seems like a backward step. In what scenario is it preferable to reference the (possibly re-assigned) window property of the global object rather than the global object itself?
What if all of your methods were "private" except the ones you manually expose through M.Class.API?
function _getParam(){
return _param2;
}
function _setParam(e){
_param2 = e;
}
function publicMethod(){
console.log("public method");
}
M.Class.API = {
getParam : _getParam,
setParam : _setParam,
publicMethod : publicMethod
}
publicMethod(); // succeeds
this.publicMethod(); // still fails
M.Class.API.publicMethod(); // still works, still is kludgy
You should also be aware that returning an anonymous object from a function may have unintended consequences when calling that function with the new keyword. See this Stack Overflow question.

How to break closures in JavaScript

Is there any way to break a closure easily in JavaScript? The closest I have gotten is this:
var src = 3;
function foo () {
return function () {
return src; }
}
function bar (func) {
var src = 9;
return eval('('+func.toString()+')')(); // This line
}
alert(bar(foo()));
This prints '9', instead of '3', as a closure would dictate. However, this approach seems kind of ugly to me, are there any better ways?
Your code is not breaking the closure, you're just taking the code the makes up a function and evaluating it in a different context (where the identifier src has a different value). It has nothing at all to do with the closure that you've created over the original src.
It is impossible to inspect data that has been captured in a closure. In a sense, such data are even more "private" than private members in Java, C++, C# etc where you can always use reflection or pointer magic to access them anyway.
This could be useful if you are trying to create multiple similar methods in a loop. For example, if you're creating a click handler in a loop that relies on a loop variable to do something a little different in each handler. (I've removed the "eval" because it is unnecessary, and should generally never be used).
// Assign initial value
var src = 3;
// This is the regular js closure. Variables are saved by reference. So, changing the later will
// change the internal value.
var byref = function() {
return src;
}
// To "break" the closure or freeze the external value the external function is create and executed
// immidiatly. It is used like a constructor function which freezes the value of "src".
var byval = function(s) {
return function() { return s };
}(src);
src = 9;
alert("byref: " + byref()); // output: 9
alert("byval: " + byval()); // output: 3
As others said this doesn't seem to be the right thing to do. You should explain why you want this and what you want to achieve.
Anyway, one possible approach could be to access properties of an object inside your function. Example:
var src = 3;
function foo (context) {
context = context || window; // Fall back to the global namespace as default context
return function () {
return context.src;
}
}
function bar (func) {
var context = {src: 9};
return func(context);
}
alert(bar(foo));
If you want to access a variable in a wider scope, just don't reuse the variable name in a narrower scope.
That's how it is supposed to work. Work with it instead of trying to fight it.
Here is the code see if you can understand , closures defined within a loop .
var clicked = false;
for(var i=0;i<temp.length;i++){
(function(index){
if(clicked) return false;
$(temp[index]).on('click',function(){
if($(temp[index]).text()=="" && !$(".cell1").val()){
$(this).text(player1Val);
$(".cell1").val(true);
console.log("first player clicked ");
clicked = true;
$(this).off();
for(var j=0;j<temp.length;j++){
$(temp[j]).off('click');
}
return false;
}
else return false;
});
})(i);
}

Categories