I know we can use Ctrl+Click or Ctrl+B in NetBeans, but it doesn’t work for me when I’m writing javascript files.
And I’m not the only one (sadly that question has no reply).
I can see the functions on the Navigator, but I can’t use “Go to declaration”.
I’m declaring my functions this way:
function anyName(params...) { ... }
I tried changing to this style:
var anyName = function (params...) { ... }
But that didn’t work either.
I’m using Netbeans 6.9.1.
More info:
NetBeans supports “Go to declaration” in javascript.
As I said, the function is recognized because I can see it in the Navigator.
I can use Ctrl+O and then search for my function, and NetBeans can find it when I do that. I’m using this right now as a poor replacement for “Go to declaration”.
I’ve noticed that I don’t have code completion either. Following the above example, if I write “an” (Ctrl+Space) I can see a lot of functions and methods but I can’t find my function (anyName).
I think I’m doing something really wrong, but I don’t know what.
I think the short answer is NetBeans doesn't have a good parser for JavaScript. JS is such a loosely typed language, it could be incredibly difficult to "Go To" the actual definition of a function. Take these examples:
function callStuff(myFunc)
{
myFunc(); //Where does this go?
}
callStuff(function () { window.alert(123); });
Or:
var x = {
X: function () { },
Y: function () { },
};
x.Z = function () { };
x.Y(); //Where do I go?
x.Z(); //How about this?
Or maybe:
string s = "window.alert(123);";
var callback = Function(s);
callback(); //Now we just made a function with a string, weird..
So as you can see, a JavaScript IDE would need to have an immense amount of knowledge on the run-time execution of your script to figure out exactly where a function was defined. There's a few IDEs that fake it pretty well if you use standard syntax or very obvious function declarations, but I've yet to see anything incredibly useful in this area. It's most likely not really something NetBeans has made an effort to support, since it's such a Java-centric IDE.
The problem seems to be in defining everything as “global”. If you work in your own namespace — that is, create a global object and define everything there — then Netbeans can understand better where your code is and can also give you type hints.
Related
I'm learning Javascript and I wrote the following code:
if (mystring.len > 0) {
// do stuff
}
I accidentally used .len instead of .length. To my surprise, no error was raised. mystring.len returned undefined and this made the comparison fail but the code kept right on running. I would prefer an actual error to be raised so I can fix the code. Adding "use strict" didn't help, nor did jslint.
I know there are ways to actively check whether or not a property exists, but that's not what I'm looking for. I want Javascript to tell me when I've made a typo in a property name.
Is there a way to cause Javascript to give an error in this case?
Nope - that is how JavaScript works and it's incredibly useful. Who is to say that checking len is something that needs fixing? Consider:
if(mystring.len === undefined) {
mystring.len = "Test";
}
The best you can do is to simply check that the thing is defined before using it:
if(mystring.len !== undefined) {
}
I appreciate the strangeness, and how it doesn't feel robust (having originally come from a C# background) but there isn't a lot you can do unfortunately. The fact that JavaScript is case sensitive makes this even more frustrating. You will learn to live with it though!
If you really really wanted to run some static analysis then you could considering creating a transpiler (e.g. Babel) extension to run this sort of analysis - but it would get really difficult if you ever expected something to be undefined which I find is common place.
edit
Here's a real example that I'd use where undefined is useful. I'm working with a library that needs to move stuff from one location to another. It can't do that unless the original location has been specified, so I might write something like the following, initializing values if I don't have them for some reason:
function update(node) {
if(node.x === undefined) { node.x = 0; }
node.y = node.y || 0; // This is the shorthand way I'd actually write it
// Do some other stuff
};
"use strict" (in my experience) is used so that variables that aren't explicitly declared/instantiated that are then referenced will throw errors (else, JS would just make a new var on the fly). So that wouldn't help here.
This sounds like an error that would typically be picked up by a compiler in other languages, but since JS is interpreted, you won't have that kind of explicit error checking unless you're in a beefy IDE. Are you using a text editor or something to write JS?
Thats not the way JavaScript considers your above code. Every variable in JS is an object. So, when you do mystring.len, its actually trying to access the len property of mystring obj and when it doesn't find that property, it will return undefined - which is how it should be. Thats why you will not be able to find any error using JSLint.
Just to give you an example -
var myObj = {name: 'Hello', id: 1};
console.log(myObj.name); // Returns 'Hello'
console.log(myObj.text); // 'undefined'
In order to prevent such code from giving you any errors, you can easily use the hasOwnProperty() method like follows-
if(myObj.hasOwnProperty('text')) doSomething();
Since myObj doesn't have any property text, the doSomething() function will never be called.
This is the behaviour of JavaScript as mentioned by many/all answers. However there is an option to prevent new properties you might want to try:
Object.seal https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal
The simple answer is JavaScript is not ment to be typesafe...You shouldn't check it, but if you still want to check you can do it by:
if ('len' in mystring){
}
You should look into Typescript if you ask this question...
Dear Javascript programmers,
Google's Closure Library is always good for driving people crazy. I hope you can help me on this issue:
I want to catch the ondevicemotion-Event by javascript within a function within the Closure lib.
Without Closure everything works fine with the following code which I grabbed from this page (thanks to the author): http://www.peterfriese.de/how-to-use-the-gyroscope-of-your-iphone-in-a-mobile-web-app/
The following snippet shows "my" code:
if (window.DeviceMotionEvent != undefined) {
console.log("DME");
window.ondevicemotion = function(e) {
console.log("ODM");
// handle events like e.rotationRate
...
}
}
This works perfectly in a standalone html page. Both console.logs are triggered.
In contrast, Closure seems to have a problem with window.ondevicemotion = function(e) { because the console logs "DME" but not "ODM".
There are no compiler warnings or errors.
Has anybody recognized such a problem, too? I sadly have no idea why Closure acts so stupid (more probably I am so stupid). ;-)
Thanks for reading! Any help appreciated!
Running in ADVANCED_COMPILATION, the Closure Compiler minimized and obfuscated window.ondevicemotion for me, so I'll assume that is your problem as well. There are two ways to step around this:
1. Use bracket notation to set / access the property.
The Closure Computer will not rename any properties that are referenced via the bracket notation. The following should not get obfuscated (though, potentially, it could get rewritten as window.ondevicemotion):
window['ondevicemotion'] = function(event) { ... }
2. Use an extern to let the compiler know not to rename this property.
Similar to the situation above, the Closure Compiler takes a hint and doesn't rewrite the property, leaving it as is. This, however, has a nice benefit of giving you some type checking, since you're defining what the signature of the extern is to the Closure Compiler:
/**
* #param {goog.events.Event} event
*/
window.ondevicemotion = function(event) {};
The decision of which one to use is ultimately yours. In this scenario I would most likely go for the second option and only go back to the first if there was some reason you could not use externs.
I'm trying (perhaps in vain) to come up with a way to use the publish-subscribe pattern while a) using no libraries and b) minimizing boilerplate code in modules that use it. So far the best I've come up with is this:
var handle = document.createElement();
var unsubscribe = AwesomeModule.subscribe(handle);
handle.addEventListener('awesome', function() {
console.log('awesome');
});
This will work pretty well, except that people using AwesomeModule might be confused by having to provide a random DOM element that isn't used as an element.
I tried the following and it doesn't work too well:
var handle = Object.create(EventTarget);
var unsubscribe = AwesomeModule.subscribe(handle);
handle.addEventListener('awesome', function(){
console.log('awesome')
});
I get TypeError: Object [object Object] has no method 'addEventListener'. Interestingly enough, it doesn't seem to look in the prototype chain even though handle has EventTarget as its prototype.
Why doesn't this work? Is there a way implement EventTarget with pure JS? Can it be done in a single line of code that won't horrify users of AwesomeModule?
EDIT: I don't know why it didn't occur to me last night, but I suppose EventTarget being an interface means that it doesn't have implemented code. What's confusing is that in the Chrome debugger console Object.create(EventTarget) makes an object that appears to have addEventListener in is prototype chain. Maybe its lying. Can anyone explain this behavior? Can anyone explain why W3 chose not to make EventTarget a concrete "class"?
It looks like the answer to my original question is "yes." Since JavaScript doesn't have an inheritance model like Java which does compile-time checks for legal implementation, I suppose any Object can implement an interface merely by having methods with the same name. However, doing this would constitute making a library since the addEventListener code isn't implemented in EventTarget (I had previously assumed it was). Since there seems to be no cross-browser way to get a vanilla EventTarget, I will probably use window.addEventListener in conjunction with custom events.
The source is located here: https://code.google.com/p/chromium/codesearch#chromium/src/third_party/trace-viewer/src/base/event_target.js&sq=package:chromium&type=cs&l=18
If you can't modify it, you can always replicate it.
Here's a simple set of routines that works well.
with a small polyfill for IE9 and 10, support is decent.
you can incorporate these functions into your project as needed, i don't think it constitutes a library, or i wouldn't post this.
var on = addEventListener.bind(window),
off = removeEventListener.bind(window),
emit = function(name, val) {
dispatchEvent(new CustomEvent(name, {
detail: val
}));
};
// demo:
on("test", function(e){ alert(e.detail);});
emit("test", "Number is " + Math.random());
i don't think it can get much simpler (~180 chars) without sacrificing speed or library compatibility.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I can't find any accessible examples showing how two (or more) different modules are connected to work together.
So, I'd like to ask whether anyone has time to write an example explaining how modules work together.
In order to approach to Modular design pattern, you need to understand these concept first:
Immediately-Invoked Function Expression (IIFE):
(function() {
// Your code goes here
}());
There are two ways you can use the functions. 1. Function declaration 2. Function expression.
Here are using function expression.
What is namespace?
Now if we add the namespace to the above piece of code then
var anoyn = (function() {
}());
What is closure in JS?
It means if we declare any function with any variable scope/inside another function (in JS we can declare a function inside another function!) then it will count that function scope always. This means that any variable in outer function will be read always. It will not read the global variable (if any) with the same name. This is also one of the objective of using modular design pattern avoiding naming conflict.
var scope = "I am global";
function whatismyscope() {
var scope = "I am just a local";
function func() {return scope;}
return func;
}
whatismyscope()()
Now we will apply these three concepts I mentioned above to define our first modular design pattern:
var modularpattern = (function() {
// your module code goes here
var sum = 0 ;
return {
add:function() {
sum = sum + 1;
return sum;
},
reset:function() {
return sum = 0;
}
}
}());
alert(modularpattern.add()); // alerts: 1
alert(modularpattern.add()); // alerts: 2
alert(modularpattern.reset()); // alerts: 0
jsfiddle for the code above.
The objective is to hide the variable accessibility from the outside world.
I would really recommend anyone entering this subject to read Addy Osmani's free book:
"Learning JavaScript Design Patterns".
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
This book helped me out immensely when I was starting into writing more maintainable JavaScript and I still use it as a reference. Have a look at his different module pattern implementations, he explains them really well.
I thought i'd expand on the above answer by talking about how you'd fit modules together into an application. I'd read about this in the doug crockford book but being new to javascript it was all still a bit mysterious.
I come from a c# background so have added some terminology I find useful from there.
Html
You'll have some kindof top level html file. It helps to think of this as your project file. Every javascript file you add to the project wants to go into this, unfortunately you dont get tool support for this (I'm using IDEA).
You need add files to the project with script tags like this:
<script type="text/javascript" src="app/native/MasterFile.js" /></script>
<script type="text/javascript" src="app/native/SomeComponent.js" /></script>
It appears collapsing the tags causes things to fail - whilst it looks like xml it's really something with crazier rules!
Namespace file
MasterFile.js
myAppNamespace = {};
that's it. This is just for adding a single global variable for the rest of our code to live in. You could also declare nested namespaces here (or in their own files).
Module(s)
SomeComponent.js
myAppNamespace.messageCounter= (function(){
var privateState = 0;
var incrementCount = function () {
privateState += 1;
};
return function (message) {
incrementCount();
//TODO something with the message!
}
})();
What we're doing here is assigning a message counter function to a variable in our application. It's a function which returns a function which we immediately execute.
Concepts
I think it helps to think of the top line in SomeComponent as being the namespace where you are declaring something. The only caveat to this is all your namespaces need to appear in some other file first - they are just objects rooted by our application variable.
I've only taken minor steps with this at the moment (i'm refactoring some normal javascript out of an extjs app so I can test it) but it seems quite nice as you can define little functional units whilst avoiding the quagmire of 'this'.
You can also use this style to define constructors by returning a function which returns an object with a collection of functions and not calling it immediately.
Here https://toddmotto.com/mastering-the-module-pattern you can find the pattern thoroughly explained. I would add that the second thing about modular JavaScript is how to structure your code in multiple files. Many folks may advice you here to go with AMD, yet I can say from experience that you will end up on some point with slow page response because of numerous HTTP requests. The way out is pre-compilation of your JavaScript modules (one per file) into a single file following CommonJS standard. Take a look at samples here http://dsheiko.github.io/cjsc/
You can find Module Pattern JavaScript here http://www.sga.su/module-pattern-javascript/
This is the source code for Underscore.js' delay function:
_.delay = function (func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function () { return func.apply(null, args); }, wait);
};
How is this any different from setTimeout? Why does Underscore.js need delay?
It's a cross browser way of being able to pass extra arguments which will appear as the arguments to the callback, like setTimeout(). This doesn't work in IE.
It can make your code prettier...
setTimeout(_.bind(function() { }, null, "arg1"), 1e3);
...vs...
_.delay(function() { }, 1e3, "arg1");
I agree that it's one of the less useful Underscore methods, which are outlined in Naomi's answer.
Why does Underscore.js have a delay function?
Because dumb. This particular underscore.js method seems pretty stupid.
Cons
additional function in lib means larger code base
larger code base means more to maintain and more possible bugs
code that uses this function now has a dependency on that lib
lesser/nil improvement over native API means low cost:gain ratio
new apis to learn
Pros
this section intentionally left blank
I would just learn to use javascript and do something like
var hello = function() {
console.log("hello");
};
var delay = 1000;
window.setTimeout(hello, delay);
Simple, right? Underscore.js is sometimes pretty useless. Honestly, window.setTimeout is perfectly useful just the way it is.
Here's another example to show how to pass an arg to the function
var Cat = function(name) {
function meow(message) {
console.log(name, "says meow!", message);
}
this.meow = meow;
};
var duchess = new Cat("Duchess");
window.setTimeout(duchess.meow.bind(duchess, "please feed me!"), 2000);
// 2 seconds later
// => Duchess says meow! please feed me!
If you can't depend on .bind you can use a closure too
window.setTimeout(function() {
duchess.meow("please feed me!");
}, 1000);
Wow, that was difficult, though. I'm going back to underscore and lodash and jquery. This JavaScript stuff is tough !
aes·thet·ics
The author of that library, who chose to spend his/her spare time to open source it, talk about it, use it as a way to introduce people to javascript and perhaps get someone to have a light-bulb moment around closure scope thought the library's attractiveness was enhanced by having this.
Arguing the relevancy of this function in isolation is like arguing the relevancy of a painting or other piece of craftsmanship. Some may like it, others may not.
You are free to like it or not. I, personally, prefer just-get-to-the-point libs.
_.delay, _.defer, _.throttle, _.after have a flow IMHO that reads better than window.
On-top of this, generally I also like writing node server side (nodejs) and not have to shift/in/out of mode... try using window.timeout in node and see what happens.
Not much, although it fits thematically with defer, debounce, and so on. This means you can use the underscore wrapping notation:
_(yourfunction).delay(1000);
Also it doesn't seem like it will let you get away with a string argument, which would call eval.