I have a slightly embarrassing question relating to a simple Javascript function I have come across:
Passport.prototype.use = function(name, strategy) {
if (!strategy) {
strategy = name;
name = strategy.name;
}
if (!name) throw new Error('authentication strategies must have a name');
this._strategies[name] = strategy;
return this;
};
I believe the purpose of this function is to give a strategy a name, overriding a default name it may have.
I believe the first part of the function is essentially assigning strategy.name to name, given the case that strategy is undefined if(!strategy){}. This does not feel intuitive to me. How can strategy.name be defined if this code is only ran if strategy is not defined? Ie. can an undefined object have a defined property—or am I looking at this incorrectly?
As a side note—I've been scouring the web trying to figure out the use of the _ throughout javascript. I know the underscore.js library is pretty popular, but that library hasn't been loaded so this underscore must signify something else.
Anyways, any help is appreciated. Thanks!
For organization sake's, let's formalize the comments section (btw, why do so many people answer via comments nowadays?)
Argument overloading
This is (unfortunately) quite common in Javascript. It's a way to provide two interfaces with the same function. In my opinion, this generally leads to confusion.
Nonetheless, in this case, the author wants to offer two signatures:
Prototype.use(strategy: Object)
and
Prototype.use(name: String, strategy: String)
Allowing a caller to either:
Passport.use("name", "strategy");
or
Passport.use({ "name": "name" });
Therefore, if the second argument is falsy (if (!strategy)) then use the first argument instead (strategy = name;).
"""Private""" variables
Javascript lacks "private" variables (except for closures) so using an underscore to prefix your _property indicates that it should not be accessed by external code, i.e. "use at your own peril, may break".
Related
From what I've read ES6 symbols "only use is to avoid name clashes between properties"..
If this is the case and I wanted to check for name collisions on an object, why not just use a simple function to check, and then use a different property name if the check returns true? Why the introduction to an entire new data type ? (I'm sure I'm naive in asking this, but I don't understand)
Example:
var obj = {
prop1: "some prop",
prop2: "some prop",
prop3: "some prop"
}
function propChecker(propName) {
if (propName in obj) {
console.log("Pick a different property");
}else{
console.log("Property name is available");
}
}
In this link the author of the accepted answer says "EcmaScript itself can now introduce extension hooks via certain methods you can put on objects (e.g. to define their iteration protocol) without running the risk of clashing with user names."
I am curious what this means in more simple-speak.
I'm guessing the "real" use of symbols is that of a tool to help those connected to the standards body implement new features without breaking preexisting code.
[1]: https://stackoverflow.com/questions/21724326/why-bring-symbols-to-javascript
Why not just use a simple function to check, and then use a different property name if the check returns true?
Because that would mean everyone needed to do these checks. And there needed to be a protocol on how to use a different property name.
Also, one needs to assume that existing code already uses all possible property names. If you want to introduce a new, standard method name to use in an iteration protocol, which one could you choose? There is no name that you can pick where it is assured that it doesn't collide with anything.
I'm guessing the "real" use of symbols is that of a tool to help those connected to the standards body implement new features without breaking preexisting code.
No, you don't have to be connected to the standards body to use symbols. Everyone can introduce his own property names that don't clash with other code. They're useful for all kinds of libraries that need to work with arbitrary objects and don't want to break encapsulation.
New to javascript. Let's say I have a constructor like this:
function Dependent(dependency) {
this.doSomething = function(x) {
dependency.doSomethingReal(x);
}
}
var impl = new SomeImplementation();
var dependent = new Dependent(impl);
console.log(dependent.doSomething(3));
My understanding is that there is nothing in the language that can help to ensure that impl can in fact fulfill its responsibilities (actually has a method called doSomethingReal that takes an argument).
A few questions come up:
In the constructor-function should I manually check the dependency argument to ensure that it has all the things Dependent requires?
Should I just not worry about it?
How do the other libraries deal with this situation? For example, I know there are a couple DI projects...or MVC projects that for example require their view objects to implement certain well-known-methods.
I realize that I can just pass a function into the constructor. In other words, if dependency was a function then we'd just invoke it. Is that the safest way to do it? I don't think that's what the MVC projects do...also there are times that it makes sense to pass in an object.
You can use instanceof to check if an object is an instance of another one.
For example, within your code:
function Dependent(dependency) {
// here we could check that dependency is an instance of SomeImplementation
if (!(dependency instanceof SomeImplementation))
throw "dependency must be an instance of SomeImplementation";
this.doSomething = function(x) {
dependency.doSomethingReal(x);
}
}
var impl = new SomeImplementation();
var dependent = new Dependent(impl);
console.log(dependent.doSomething(3));
In javascript it's also common to use the 'duck typing' method to validate an object. For example:
console.log (
'isABird' in duck &&
'walks' in duck &&
'swims' in duck &&
'quacks' in duck ?
"juhm... I'm pretty sure we're dealing with a duck" :
"meh... since I a expect a duck to be a bird, walks, swims and quacks, then this buddy is definitely not a duck"
);
Well, as far as I have understood it, Duck Typing would be the natural way to deal with this problem in JavaScript since JavaScript is not a strict typed language.
In consequence this would mean that you indeed just accept, that JavaScript is loosely typed and that you will have to deal with runtime-errors when you try to access a method on an object that does not have this method. (Your option 2)
Apart from that, you could use a pattern that tries to simulate interfaces or abstract classes in JavaScript which works like you have suggested in option 1 and which is described here in detail:
http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#decoratorpatternjavascript
(Chapter "Pseudo-classical Decorators")
But this would also just lead to runtime-errors. The exceptions might just rise up a little earlier but not at "compile time". So in both designs you will need to test your application in order to find type-related-errors.
So I tent to accept that Duck Typing.
First of all, no, I'm not trying to create any sort of Java-like interface for my JavaScript code. I've seen those questions all over, and while I'm still a relative novice to JavaScript, I know those aren't part of the language.
However, I'm curious what the actual intended use of the interface keyword is. For example, Math is an interface, containing definitions (but not implementations). I believe (and may be totally wrong) that these are there to provide a means for the definers of the language to enforce a set of behaviors to be implemented in various JavaScript engines. Is that correct?
Furthermore, I have a desire to have a "static class" that contains a bunch of utility methods. I like that Math.sqrt(3) has an outer namespace ('Math') which is capitalized, and a number of logically similar methods and values in it. Maybe it's just my Java/Ruby background that makes me want a capital on the grouping objects. Is that bad form?
var ShapeInspections = {
isSymmetrical: function (s) {
// determine if shape is symmetrical
},
numAngles: function (s) {
// return the number of angles
}
}
A purely contrived example, but is it anti-idiomatic to name the "module" this way?
Okay, so as with other answers, you know that the keyword interface has no real use case in Javascript world, yet.
Your Math example made me suspicous that you are talking about a design pattern, called Module Pattern, widely used for scoping Javascript code. There are many ways of making your code modular. For example just like OddDev answered you , the famous Prototype Pattern can embed your code in a modular fashion (just like your Math example). Here is the Revealing Prototype Pattern example with also private variables and functions for additional flexibility:
/* Example from:
http://www.innoarchitech.com/scalable-maintainable-javascript-modules */
var myPrototypeModule = (function (){
var privateVar = "Alex Castrounis",
count = 0;
function PrototypeModule(name){
this.name = name;
}
function privateFunction() {
console.log( "Name:" + privateVar );
count++;
}
PrototypeModule.prototype.setName = function(strName){
this.name = strName;
};
PrototypeModule.prototype.getName = function(){
privateFunction();
};
return PrototypeModule;
})();
but that is not all. Other options include Scoped module pattern, POJO module pattern and many more. Have a look at How to Write Highly Scalable and Maintainable JavaScript: Modules, it has a very simple and yet thorough set of examples.
So far, we talked about plain Javascript. If you have the ability to use libraries in your code, then amazing set of libraries such as Requirejs, CommonsJS are there to help you on this with out-of-the-box functionalities. Have a look at Addy Osmani's post about Writing Modular JavaScript With AMD, CommonJS & ES Harmony.
The interface keyword in javascript is a FutureReservedWord, so it does absolutely nothing right now, though that may change in the future specifications. (See ECMAScript 5.1, section 7.6.1.2). In the ES6 draft, this is also the same.
As for you module, this is a perfectly idiomatic solution. It is always a good idea to "namespace" your functions, as it keeps the global scope as clean as possible.
I believe (and may be totally wrong) that these are there to provide a means for the definers of the language to enforce a set of behaviors to be implemented in various JS engines. Is that correct?
No, this is not correct. Things like "Math" etc. are objects containing functions. If you use for eyample "Math.pow(...)" you just execute the function stored in the "Math" object. Check this example:
var Math = {};
Math.prototype.pow = function(){
alert("stuff");
}
var ShapeInspections = { isSymmetrical: function (s) {
// determine if shape is symmetrical }, numAngles: function (s) {
// return the number of angles } } A purely contrived example, but is it anti-idomatic to name the "module" this way?
It's okay to name your objects like this. As already discussed "Math" is also just an object and follows these naming conventions.
To make things clear for the interface keyword:
The following tokens are also considered to be FutureReservedWords
when they occur within strict mode code (see 10.1.1). The occurrence
of any of these tokens within strict mode code in any context where
the occurrence of a FutureReservedWord would produce an error must
also produce an equivalent error:
implements let private public yield
interface package protected static
It's just reserved cause it's "may" needed in the future. So don't worry too much about it :) http://www.ecma-international.org/ecma-262/5.1/#sec-7.6
Do not confuse the "interfaces" that are specified in IDL with the interface keyword.
The latter is reserved for potential future use, but is not yet actually used in ECMAScript (not even in ES6).
I am creating an object inside of an enclosure. Also in the enclosure are private properties that the object's functions can access - and this works as expected.
My issue: I want others to be able to extend my object with functions of their own (functions from a different context), but those functions will also need access to the same private properties - and I have not been able to find a way to make this work.
I've tried various configurations of .call, and also wrapping their function in a new function, amongst other things. I feel like I've gotten close to a solution, but have just fallen short.
Here's a bit of simplified example code that accurately reflects my situation:
//extension object
//fn2 can be any function, with any number of arguments, etc.
var obj1 = {};
obj1.fn2 = function (s1, s2){ console.log(priv); };
//actual object
var obj2 = (function (){
//private property
var priv = "hello world";
//return object
var obj3 = {};
//return object's native fn (works)
obj3.fn = function (s){ console.log(priv); };
//extension happens here - but is obviously not correct
obj3.fn2 = obj1.fn2;
//return object
return obj3;
})();
//try output
obj2.fn("goodbye world"); //works
obj2.fn2("goodbye world", "thx 4 teh phish"); //fails
Any insight would be appreciated. And I totally understand if what I want just isn't possible - but it sure seems like it should be :P
EDIT: Thank you all for the responses. I fully understand that the properties are more easily accessed as public, and that normally inherited objects won't have access to them otherwise. However, since the new function is being attached to the original object I have to believe there's a way to use the original context and not the context the new function was created in.
Now, I'm the first to say that eval is evil - and, in fact, I've never used it, or even considered using it, before. However, I'm trying everything I can think of to make this work - and I stumbled across this (seemingly) working solution:
obj3.fn2 = eval(obj1.fn2.toString());
So, if I check to make sure that obj1.fn2 is a typeof function, is there any way this could be harmful to my code? It doesn't execute the function, so I can't see how - but maybe I'm missing something?
Javascript doesn't have a "protected" analog. You either get super private or completely public. From here you can choose to:
Reconsider your class design, and have the subclasses depend only on the public interface of the parent class.
Add getter and setter functions to the public interface. Not necessarily the best thing though as you might just as well make the properties public (besides best practice issues and whatnot)
Just use public properties instead. This is the "natural" way to do OO inheritance in Javascript and is usually not a problem if you use a donvention like adding an underscore to the beggining of the name. As a bonus you can use the prototypal inheritance feature (it is nice knowing how to use this instead of only closure-based classes)
function Base(){
this._priv = "Hello world"
};
Base.prototype = {
fn: function(){
console.log(this._priv);
}
}
var obj2 = new Base();
obj2.fn = function(){ ... }
I hate to answer my own question - seems like a bit of a faux pas - but c'est la vie. (because I woke up French today?)
So, while I found that the eval() solution I presented last night in the edit to my original question does seem to be a valid solution, and a proper use of eval for retaining the object's context within the new function, it is far from perfect.
Firstly, it works in FF, but both IE and Chrome seem to hate it (those were the next ones I tried, and I quit trying others after they both failed). Though I'm sure it could probably be made to work across browsers, it seems like a hassle.
Secondly, it does give quite a bit of power to the new function, and as I look at my code more I do like the idea of controlling exactly what these new functions being added to my object get access to.
Thirdly, .eval() is typically pretty slow - and it turns out that .apply() (which is typically faster) just may work well enough.
This is because I realized at some point last night that no new functions on this object will need to set any of the private variables (at least, I'm fairly certain they won't) - and .apply() works fine to pass the values through for them to read.
I'm sure there's more to it than just those 3 things, but for now I think I'm going to go with more of a 'wrapper' solution - something like this:
var f = function (){
var fauxThis = {};
fauxThis.priv = priv;
obj1.fn2.apply(fauxThis, arguments);
};
obj3.fn2 = f;
//(To be placed where I had "obj3.fn2 = obj1.fn2;")
I am certainly willing now to consider the use of eval() in very specific cases - and may even revisit this specific use of it before I make my final decision of which direction to take. (especially if I can think of a case where the private value would need to be set)
Thanks all for your input!
The quickest and easiest solution is to prefix any supposedly private properties with the underscore (_).
Personally I like to bottle my private properties into a single object which would be placed on the object, like so:
obj.publicProp = 20;
obj._.privateProp = true;
I wouldn't worry so much about it though, the underscore is basically a universal symbol for private so those using the script will know that it's private and shouldn't be touched. Or, better yet, just leave it out of the public documentation ;)
There are other methods and you can use which do emulate "true" protected variables, but they're not the best as they avoid garbage collection, and can be clunky to use.
someone asked how to get the value of a JSObject property from c. That helped me a bit.
But, does anyone know how to get the current JavaScript name of an object from c?
example:
var foo={prop:'bar'};
then somewhere for example in jsapi.cpp:
JS_somemethod(JSContext *cx, JSObject *obj){
//how do i get the name 'foo' (or the current alias) here if *obj points to the foo (or whatever alias name) object?
}
Thx for hints and answers!
Okay, just to document the question clarification from your comment I'll repeat it here:
Maybe i tell you in short my purpose: For the integration of new security system in webbrowsers i need to find out what is accessed during a common session on a website. my aim is to get something like a log which objects are accessed and how (read,write,execute). for example: window.alert (x) window.foo.bar (w) ... you now why i need the names of the variables? maybe you've got an other idea?
Just to say it up front, this is pretty tricky in general. There are a few options available to you, all of which are somewhat difficult:
Use the debugging API, either via the cool new debugger object API or via jsdbgapi.cpp (the complex and slightly gross interface that firebug uses). You can use debugger functionality to trap on all property accesses, functions calls, and local references in order to dump out interesting properties of objects.
If you're only interested in the way that your (user defined) objects are accessed, you can use Proxies that wrap your objects and dump out the accesses being performed on them. A slightly more powerful and low-level version of proxies are actually used in the browser to implement our security features. (Additionally, most of the proxy functionality is accessible for custom-created objects in the JSAPI via our meta-object-protocol, but proxies are just a much cleaner version of that same functionality.)
Instrument the interpreter loop in jsinterp.cpp. A lot of research-like work turns off the JITs and instruments the interpreter loop, because it's fairly understandable if you've worked on language implementations before. Unfortunately, it's not always easy to translate what you want to do into interpreter loop instrumentation at first, even if you have experience with language implementations.
The debugger object is definitely my favorite option of those I've listed here. If you go with that approach and end up getting stuck feel free to visit #jsapi in irc.mozilla.org and try to get a hold of jorendorff or jimb, they're a) awesome and b) the creators of the debugger object.
Without looking too closely at the API, I'm going to say that while it might be possible to do this in some very basic cases, you don't want to. This is why:
In Javascript, as in most languages, variables point to values. Variables are not the values themselves. The object is not in any way inherently related to the name foo.
For instance, you can do
var foo = {prop: 'bar'};
var fooo = foo;
var foooo = foo;
var quux = {q: foo, r: foo, s: [foo]};
All of those foos are now the exact same foo; which one do you want back? There's no API call for that because it's too ambiguous and not terribly useful.
However, if you really want to find one of the global variables holding a value, you can try iterating over the keys on the global object and testing them for the value.
for(var key in this){
if(this[key] == myval){
var myname = key;
}
}
You'd have to translate this into your API calls or else put it in a function and call that through the API.
The more simple and straightforward solution would be to figure out what you want to do with foo later on, and pass in a callback function that will do that, e.g. with JS_CallFunction.
tl;dr: Previous paragraph.