I am making this function in java script and keep geting the synatx error don know why please help since i am new to java script. I don knw wat is wrong. Below is the code.
function create(sourceCanvas) {
var JSARRaster = new NyARRgbRaster_Canvas2D(sourceCanvas);
var JSARParameters = new FLARParam(sourceCanvas.width, sourceCanvas.height);
var JSARDetector = new FLARMultiIdMarkerDetector(JSARParameters, 120);
JSARDetector.setContinueMode(true);
return {
"create": create(),
}
This code is unintelligible. I don't think it's a syntax problem, so much as a complete lack of understanding of how functions work. You are using objects and a function, and it seems like you don't really understand either. I'm not saying this to be rude, just stating my perception of your question. In fact, I'll try to break it down for you.
function create(sourceCanvas) {
This is the function definition. It means that when you use the keyword "create" the computer should link to the block of code in between the curly braces {}. You have an opening curly brace, but no closing one, so that is a syntax error. In the create function definition you have listed "sourceCanvas" as an argument. That means that you are telling the computer that you need that variable to execute the code in the body of the function.
var JSARRaster = new NyARRgbRaster_Canvas2D(sourceCanvas);
var JSARParameters = new FLARParam(sourceCanvas.width, sourceCanvas.height);
var JSARDetector = new FLARMultiIdMarkerDetector(JSARParameters, 120);
JSARDetector.setContinueMode(true);
return {
"create": create(),
}
Here you are calling the "create" function. But you don't have any arguments listed. Remember how you need a "sourceCanvas" argument? That will cause another syntax error. Also you are calling the "create" function inside the "create" function. That will cause an infinite loop that will crash your machine.
{ "create": create(), } is an object. It has an attribute "create" and the value of "create" is whatever the function create() returns. Since there is only one attribute, you don't need the comma. That's another syntax error.
I don't know what your function is supposed to do, but here is a version that will compile:
function create(sourceCanvas) {
var JSARRaster = new NyARRgbRaster_Canvas2D(sourceCanvas);
var JSARParameters = new FLARParam(sourceCanvas.width, sourceCanvas.height);
var JSARDetector = new FLARMultiIdMarkerDetector(JSARParameters, 120);
JSARDetector.setContinueMode(true);
return {
JSARRaster: JSARRaster,
JSARParameters: JSARParameters,
JSARDetector: JSARDetector
}
}
According to your code here:
object [object Object] is not a function in javascript
Your code is laid out like this:
function create() {
return {
detect: detect,
getCameraMatrix: getCameraMatrix,
}
}
return { create: create };
So that bottom "return" is outside the create function.
Return has to be in a function.
Related
I'm new to JavaScript programming.I wrote an IIFE that will help me improve my understand. My intention is to define a $ function that when called will call itself as a constructor. When the code is run, it generates an error 'Too much recursion'. I don't know what the problem is.
(function() {
//check the global host object
var root = this;
var inside = "inside";
var $ = function () {
return new $(); //this line generates an error 'Too much recursion.'
}
$.check = function(obj) {
console.log(inside);
}
//add the $ to global object
root.$ = $;
}).call(this);
var ins = $();
console.log(ins);
var $ = function () {
return new $(); //this line generates an error 'Too much recursion.'
}
This function is repeatedly calling itself, which is why you see the Too much recursion. error. You aren't distinguishing between a regular function call and a new call.
My intention is to define a $ function that when called will call itself as a constructor.
The simplest way is to explicitly check this:
var $ = function $() {
if(!(this instanceof $)) return new $();
// ... from this point on, behave as if called via new
}
this line generates an error 'Too much recursion.'
Right. You have a function assigned to the $ symbol which calls the function assigned to the $ symbol. So each call (whether direct or via new) will run the code in that function, which makes another call to it, and so on until you exceed the engine's willingness to recurse. To avoid that, have $ do something else.
It's because you have created an infinite loop. By using parenthesis when returning your new var instance you are recursively calling that function with no parameters. I'm not sure what you are trying to accomplish, but you might want to have $ create a new object "{}" instead and then you can extend methods off of that reference. Look into singleton patterns, that will allow you to create a new instance of something.
*edit, and just to be clear your problem doesn't have anything to do with it being an IIFE, you would encounter this same error anywhere you tried to call a new function on itself in this manner.
Let's start from the code:
function say(name) {
var ghost=function () {
function ghost() {
alert('!');
};
return body;
};
eval("var body=''+"+name+';');
eval(name+('=('+ghost).replace('body', body)+')();');
eval(name+'();');
}
function Baal() {
if ('undefined'===typeof ghost) {
say('Baal');
return;
}
ghost();
}
say('Baal'); // or just Baal();
Looks like that saying the devil's name invoke his presence (well, maybe he needs somebody for spiritual possession) ..
As you can see the ghost doesn't exist along with Baal, but we can invoke it since there're evals in say(name).
say(name) reassigns Baal to its code body as a closure and makes it captured a ghost method, that's how things work. But I'm trying to avoid eval ..
So .. let me reword the question:
How do I make a nonexistent(and not a member or global) method invocable without using eval?
Let me rephrase your question, just to make sure I’ve got it. Given a function, you want to put a new variable in its scope, without that scope being the global scope or a scope shared between the caller and the subject, without using eval (or the equivalent new Function and other hacks depending on the environment).
You can’t.
In the case you just mentioned, you could define one function, base(), that uses arguments.callee.caller.
Don’t do that.
The short answer: You don't.
That scope is not available. If you were to attach the scope then it would be available inside of the scope used. You could then access the method handles. I assume this is not what you were looking for, but here is what that would look like. demo
function say(name){
var methods = {};
methods.Baal = function(){
alert("!");
};
return methods[name];//this could invoke as well: methods[name]()
}
var handle = say('Baal');
handle();
What your evals break down to is something along these lines (although with dynamic content from string building - this is the end result)
function say(name) {
var Baal = (function () {
function ghost() {
alert('!');
};
return function(){
if ('undefined'===typeof ghost) {
say('Baal');
return;
}
ghost();
}
})();
Baal();
}
say('Baal'); // or just Baal();
Note that the meat of what happens here is from the function Baal, namely that it calls a hardcoded ghost() which in turn calls a hardcoded alert. Why go through all of this trouble to access a hardcoded function?
A better way would be to inject this function as a callback which expects some parameters to be injected.
jsFiddle Demo
function say(callback){
var params = "!";
if( typeof callback == "function" ){
callback(params);
}
}
say(function(params){
alert(params);
});
It's very difficult for me to read through your code and figure out what you are trying to accomplish with it, but it appears that you are trying to introduce a variable into the current scope so that you can call it. You cannot do this in javascript with the method that you demonstrated. Scoping only ever "flows down". By that I mean that a variable or function defined within a function will only be available to that function and any other functions defined therein. Your function named ghost will only ever be available within the function where it is defined, regardless of when that function is evaluated.
What you can do, however, is write a function that returns a function. You can then call that function and assign the result to a variable in the scope where you want to expose functionality. Doing that would look something like this.
function defineSpecialAlert() {
return function(name) {
alert(name + "!");
};
}
var newlyDefinedMethod = defineSpecialAlert();
newlyDefinedMethod("Baal");
So if I understand, it seems like you want to create an alias of eval: Something like
#Note this code is not intended as a solution, but demonstrates
#an attempt that is guaranteed to fail.
#
function myAlias(ctx) {
eval.call(ctx, 'var ghost = 42');
}
myAlias(this);
alert(ghost);
Javascript allows many funky sleight-of-hand tricks especially with closures, but this is maybe the one impossible thing that javascript cannot do. I've tried at length to do this exact same thing, and I can tell you that you'll run into nothing but complaints from the browser, saying that eval cannot be re-contexted or aliased in any way.
So, I want to run this script when button A is clicked. The script is stored in an Object as a string. When button A is clicked, I use eval, like: eval(Object[script]). This works fine, unless I have functions within the script, when I do, it breaks because they are not getting defined. Is there a way to get around this? I tried putting the function definition in a var and putting it at the top of the script. Now, if I simply copy my script to the console, it executes perfectly. Is there a way to execute a script as if it were typed into the console?
FYI: This is a simplification of my problem, I realize there are better ways to do what I describe here.
The best fix is to stop storing code as strings. Use functions instead.
buttonA.script = function() {
do whatever you were doing in your eval
};
// then, instead of `eval(buttonA['script'])`, say...
buttonA.script();
// or, if the name is in a variable...
var foo = 'script'; // for example
buttonA[foo]();
About the only time eval makes sense is when you have code that by its very nature has to be dynamically generated or interpreted. For the vast majority of cases, that is not true. I can only think of a case where it would be true, in fact: the textarea script testing thing mentioned in the comments.
For every other case...
obj = {
first: function() {
function test() { alert('hi'); }
test();
}
};
obj['first']();
// or simply
obj.first();
// and what's more...`test` doesn't escape and trample on stuff.
try { test(); }
catch (ex) { alert("" + ex); } says `test` is not defined
This works:
var oFunc = function (value) {
alert(value)
}
var obj = { code: "oFunc('hello')" }
eval(obj["code"]);
Or am I missing something?
Update
This also works
var obj = { code: "var oFunc = function (value) {alert(value)}; oFunc('hello')" }
eval(obj["code"]);
In your code alert(hi) should be alert("hi")
obj = {
first: 'function test() { alert("hi") } test();'
}
eval(obj["first"]);
DEMO.
I was reading another question, and I saw this:
var basketModule = (function() {
var basket = []; //private
return { //exposed to public
addItem: function(values) {
basket.push(values);
},
getItemCount: function() {
return basket.length;
},
getTotal: function(){
var q = this.getItemCount(),p=0;
while(q--){
p+= basket[q].price;
}
return p;
}
}
}());
Can you please explain why does he wrap the function in ( and )'s? Also, what is the purpose of that return? Couldn't he just write self.addItem = ... and so on?
When you wrap a function with parantheses, and add () to the end of it, it's a self executing function.
(function() x() {
//do something;
})();
And, by returning he's making basket variable somewhat private. Try getting basketModule.basket from anywhere else, and you'll get undefined.
That is called javascript Module Pattern. Defining a function and calling it immediately to prevent variables to be in the global space or to define a function name.
Note parentheses in the last line: (). The function is defined and immediately called:
(function() { })();
return { ... } returns an object having a method addItem
The intention of the code is to create an object with three methods. addItem,getItemCount and getTotal. They all depend on state represented by basket.
if basket was defined globally that state would be exposed (and there could only ever be one variable basket. both of those can lead to issues so by wrapping the entire declaration the state is encapsulated and only accessible from the created object.
There are other ways of achieving the same and the pro's and con's are related to style and how many objects of that particular type you're going to need.
wrapping the function(){}() is required since function(){}() will not parse
I have some javascript code (within an object) :
toggle: function() {
var me = this;
var handler = function() { me.progress() };
me.intervalId = setInterval(handler, me.intervalTime);
//...More code
}
I'm kind of new to javascript, so doing the above as far as I can tell actually passes the me variable into anonymous the function. I was wanting to see if there is a more declarative way to do so? I wanted something along the line of:
var handler = (function(o) { o.progress();})(this));
but that doesn't seem to be working... Am I missing something? Is this a case where "this is the way the language works so just declare a local variable and deal with it"?
UPDATE:
The source to my problem was/is my unclear understanding of scope and closures in javascript. I found this article to help me understand a little more.
You can use ".bind()":
var handler = function() { this.progress(); }.bind(this);
New browsers have "bind()", and the Mozilla docs have a solid implementation you can use to patch older browsers.
The reason
var handler = (function(o) { o.progress();})(this));
doesn't work because it just immediately calls the anon function, therefore immediately calling o.progress() and assigns the return value of the anon function (undefined) to handler. You need to return an actual function from the outer function:
handler = (function(me){
return function(){
return me.progress();
}
}(this));
On the flip side this is equivalent and just as bad looking as bad looking as the variable assignment (but can still be useful, particularly if this needs to be done in a loop, with the changing i rather than the fixed this).
BTW, if the progress function doesn't have any calls to this inside it , just doing handler = this.progress (without the parens) might suffice.
The anonymous function has access to me because it is declared inside of the outer function (the toggle function); it is closed over by the outer function.
Your handler function will be called by setInterval, which passes exactly zero arguments. This means you can't use parameters in the handler function itself.
I you really want to pass me explicitly, you could write a function accepting an parameter, and have that function return an anonymous function without parameters, but which could access the creator function's parameter:
toggle: function() {
var me = this;
var handler = (function (o) { return function() { o.progress() }; })(me);
me.intervalId = setInterval(handler, me.intervalTime);
//...More code
}
But this basically adds a layer of redirection without really making it more legible. Unless you pull that creating function outside:
function createProgressHandler(o) {
return function() {
o.progress();
};
}
// ...
toggle: function() {
var me = this;
var handler = createProgressHandler(me);
me.intervalId = setInterval(handler, me.intervalTime);
//...More code
}
What you have there is a closure. The function that is created and assigned to handler keeps a reference to the me object. This is normal, everyday JavaScript, and that's the way that closures work generally.
Have you tried to return the function like this?
var handler = function(o){
return function(){
o.progress();
}
}(me);
Now you can call:
handler();