Parisitic inheritance in JavaScript - javascript

Watching a Douglas Crockford lecture on advanced JavaScript and he brings up the idea of parasitic inheritance which is essentially having constructors call other constructors to modify the object in question. Here is his code:
function gizmo(id, secret) {
secret = secret || {};
secret.id = id;
return {
toString: function () {
return "gizmo " + secret.id;
}
};
}
function hoozit(id) {
var secret = {},
that = gizmo(id, secret);
that.test = function (testid) {
return testid === secret.id;
};
return that;
}
var myHoozit = hoozit(20);
console.log(myHoozit.test(20)); //returns true
I understand the code and there is nothing too difficult to grasp here. The confusion takes place in the hoozit function. If you do not set secret = {} you will not get the a true being returned.
This is baffling because in the gizmo function, you see secret = secret || {} which should take care of this for us... but it doesn't.
Why is that short circuit not working correctly (secret = secret || {}) in the gizmo function when not being passed a second parameter in the hoozit function (breaks in both Chrome and Firefox)??

Why is that short circuit not working correctly (secret = secret || {}) in the gizmo function when not being passed a second parameter in the hoozit function (breaks in both Chrome and Firefox)??
Simple because you cannot access secret inside that.test because it does not exist in that scope:
function hoozit(id) {
var that = gizmo(id);
that.test = function (testid) {
// secret is not defined in this or in any higher scope
// hence you get a refernece error
return testid === secret.id;
};
return that;
}
The only secret object that exists is local to the gizmo function.
If you define it and just don't pass it to gizmo, then secret = secret || {} will evaluate to secret = {}, i.e. a new object is created inside the gizmo function. That value is only accessible within the gizmo function and is not related at all to the secret variable in the hoozit function. The secret object inside gizmo is a different than the one in hoozit.
function hoozit(id) {
var secret = {}, // secret object is created here
that = gizmo(id);
that.test = function (testid) {
// you never set `secret.id`, hence the comparison results in `false`
return testid === secret.id;
};
return that;
}
There is nothing wrong with secret = secret || {}, it is working as expected.

Let's look at a simpler example.
function Foo(baz){
baz = baz || {};
baz.boo = 1;
}
function Bar(baz){
baz = baz || {};
Foo(baz);
return baz;
}
If we call Bar(), we are passing an object to Foo. It then aguments the object by setting a boo property. Sweet!
Now, let's say our Bar function looks like this:
function Bar(baz){
baz = baz || {};
Foo();
return baz;
}
The only difference is that we are not passing an object to Foo. Because of this, Foo is creating an object inside its scope. We set a property on that new object, and then the function ends. The object isn't the parent scope of Bar, so Bar never knows this object is created, and has no way of accessing it. In the next few milliseconds, the object is deleted from RAM because there are no references to it.
That's not exactly the case with your question. The toString function references it. Because the outer scope is complete, it is now a local variable to that toString function. If we didn't pass a secret object, then it never leaves that scope. It must in some way be exported.
The more logical tactic would be to just create it as a property of our original object. Our secret could easily be accessed by a user that knows what JavaScript is, so we should save some headaches and use a sensible inheritance method.
If you don't know SomeFunction.call takes any number of arguments. The first is whatever you want to be this in the function, and the remainder are just the regular arguments.
function gizmo() {
this.toString = function () {
return "gizmo " + this.id;
};
};
function hoozit(id) {
this.id = id;
gizmo.call(this); // allow gizmo to manipulate this object
this.test = function (is) {
return this.id === is;
};
};
h = new hoozit(1);
console.log(h.test(1)); // true
console.log(h.toString()); // "gizmo 1"

You need secret = {}.
It's erroring at return testid === secret.id; because secret needs to exist.
The main magic you're probably looking for is, where is secret.id being populated, since all the operations are happening in gizmo(). The answer is this line: that = gizmo(id, secret);
secret is passed to gizmo and in JavaScript objects are passed by reference. This means that if you have a local object and pass that object as an argument to another function, any operations to that object will be reflected locally.
If you didn't want that to occur, you'd need some sort of copy/clone (the term clone has been used incorrectly by libraries to suggest a deep copy) of the argument. But in the example, you do want changes to secret in gizmo to update the secret in hoozit, so everything is working as it should.
Here's another way of writing it:
function gizmo(secret) { // only receive secret, which already has an "id"
secret = secret || {'id':null}; // if secret not passed create it with a default "id"
return {
toString: function () {
return "gizmo " + secret.id; // the reason why we needed a default "id"
}
};
}
function hoozit(id) {
var secret = {'id':id}, // create a object and set key "id" to hoozit's argument
that = gizmo(secret); // only pass secret
that.test = function (testid) {
return testid === secret.id;
};
return that;
}
var myHoozit = hoozit(20);
console.log( myHoozit.test(20) ); //returns true

Related

using closure to make private properties javascript

I have this prompt on code wars
"There's no such thing as private properties on a javascript object! But, maybe there are?
Implement a function createSecretHolder(secret) which accepts any value as secret and returns an object with ONLY two methods"
I'm pretty sure it wants me to use closures to achieve this and I have read about how to do this here:
Private variables and closures
https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Contributor_s_Guide/Private_Properties
This is my code:
function createSecretHolder(secret) {
return {
var _secret = secret;
this.getSecret = function(){
return _secret;
}
this.setSecret = function(secret){
_secret = secret;
}
}
}
However, I get this error:
[eval]:6
var _secret = secret;
^
SyntaxError: Unexpected token =
at Object. ([eval]-wrapper:6:22)
at
at evalScript (node.js:536:25)
at startup (node.js:80:7)
at node.js:906:3
I tried to make an object literal with a private value to hold the value of secret and mostly followed the examples from the sources I listed above. How do I create a closure with ONLY two methods to get and set data and where do I store the value of secret without adding another property?
You are trying to return an object literal, in which you cannot have an assignment statement. To have the closure property, you need to store the variable in the function scope, like this
function createSecretHolder(secret) {
var _secret = secret;
return {
getSecret: function() {
return _secret;
},
setSecret: function(secret) {
_secret = secret;
}
}
}
Now, _secret is in the scope of the getSecret and setSecret functions, because of the closure property. So they can access it.
The problem is return keyword actually returns object with a structure which you didn't follow.
try this:
function createSecretHolder() {
var _secret = secret;
return {
getSecret : function(){
return _secret;
}
,
setSecret : function(secret){
_secret = secret;
}
}
}
Using _ to prepend a property is a common naming convention JavaScript developers follow to show the intention that the property should not be altered, and it is definitely related to this prompt, but it seems like it is not hinting that it's needed and it may not be required for this challenge specifically.
The SyntaxError you're seeing is related to the _secret initialization being within the object literals rather than outside. Object literal syntax is different from variable declaration & assignment and should be mixed. You can move the var _secret = secret; to outside of and before the return statement (but still inside of the function createSecretHolder). (Super Hornet is right, but his code is missing the secret parameter, so his code would get a Reference error saying that secret is not defined.) While your attempt is slightly more declarative, you can actually do without the const _secret = secret. The first thing that the function does is to pair its argument with its parameter, in this case, declaring secret and assigning the input to it. So it is already "in closures".
Here's my take and it works almost the same, except I like to include the console.log() into my functions that I'm expecting to see a result.
function createSecretHolder(secret) {
// input: secret
// output: object (with only 2 methods)
return {
getSecret() { console.log(secret) },
setSecret(input) { secret = input }
}
}
const obj1 = createSecretHolder(5);
obj1.getSecret() // => 5
obj1.setSecret(2)
obj1.getSecret() // => 2
Same as:
function createSecretHolder2(secret) {
return {
getSecret() { return secret },
setSecret(input) { secret = input }
}
}
const obj2 = createSecretHolder2(91);
console.log(obj2.getSecret()) // => 91
console.log(obj2.setSecret(82)) // => undefined
obj2.setSecret('new Secret') // logs nothing, returns undefined
obj2.getSecret() // logs nothing, returns 'new Secret'

Javascript, getting away from 'this' and using local scope

In a typical js class, all calls to member functions must be preceded by this. I was looking at a technique that would let me create a library of inter-dependent STATIC functions and relying on closure/scope to make things a bit easier.
Example:
var Singleton={
//main entry point
// call with fn name, args...
call:function(){
var args=[];
if (arguments.length==0) {
return;
}
// get the fn name
var fn=arguments[0];
var x;
// make args array
for (x=1;x<arguments.length;x++) {
args[args.length]=arguments[x];
}
// I want to get rid of this part
// See below for what I wish
// Here I have access to fns below due to hoisting in js
// so I put them in a map...
var fns={
test:test
// etc, more like this I do not want to type/maintain
}
// ... all so I can do this
// get my function.
var fun=fns[fn];
// instead of that, I would like to "override whitespace" and
// say something like:
// var fun=['fn_name'];
// so I can index into local scope and get a fn
//
// log error if not found
if (typeof fun=='undefined') {
loge('Singleton: function not found:'+fn);
return;
}
// ok, run the function
return fun.apply(window,args);
// the test fn accesses test2() without dot notation
function test(a){
// Note: here in test fn it can access test2()
// without using this.test2() syntax
// as you would in normal objects
var s=test2();
alert(s+' test:'+a);
};
function test2(){
return 'test2';
};
}
}
I was hoping someone more familiar with advances in javascript might have advice on how to emulate an "implied but unnecessary this", it always struck me as strange that this defaults to window, and wouldn't it be nice if this could be pointed to an anonymous object with the local scope attached.
I would love to say ['localObject'] to get something in scope.
Edit:
After seeing some of the responses, I will restate this in the form of a challenge:
What I am looking for is a syntax cheat, a way to, as #Varuna put it, "1. Access static methods without using this variable i.e. they will remain global to one another. 2. Do not want to maintain a local array for static methods and want to achieve with in the local scope itself."
Put differently, I need to have the declared functions Register themselves, but I don't want to state the function name more than once. I suppose #Varuna has a solution using eval to access the local scope.
The following approach wont work:
var o={};
o['fn']=function fn(){};
o['fn2']=function fn2(){};
...because you have to state the fn name twice, but closure is preserved.
And this:
var a=[
function fn(){}
,function fn2(){}
];
Register(a);
Will not work because, AFAIK, you lose closure, ie. fn2 cannot see fn. Which also makes the following declarative style a "this nightmare":
window.MINE={
fn:function fn(){
//this?
// want to say fn2(), not this.fn2(), nor MINE.fn2()
}
,fn2:function fn2(){
//this?
}
,deeper:{
//more
}
};
But something like this might work, if you created a weird property that does the registration on assignment:
var registar=new Registar();
registar.reg=function fn(){};
registar.reg=function fn2(){};
//then access
var fn=registar.getFn(n);
// or
var fn=registar._[n];
The above relies on js properties and having access to fn.name, which is not available in all cases AFAIK.
If I understand correctly, you want to create objects that:
have static members
... which can be accessed without using the this notation
The easiest solution (assuming I've properly understood your query), would be to simply use a closure to store your stratic fields, access them directly by name, then explicitly add them as object members.
Consider:
var myConstructor = (function(){
var foo = 'someStaticField';
var bar = function(){
alert('A static method returns ' + foo);
};
return function(){
return {
foo : foo,
bar : bar
};
};
})();
var myInstance = new myConstructor();
As per my understanding, you want to:
1. Access static methods without using this variable i.e. they will remain global to one another.
2. Do not want to maintain a local array for static methods and want to achieve with in the local scope itself.
You can check whether a method exist using eval.Check Here
Only drawback is that this will be using eval method.
Code will be:
var Singleton = {
//main entry point
// call with fn name, args...
call: function () {
var args = [];
if (arguments.length == 0) {
return;
}
// get the fn name
var fn = arguments[0];
var x;
// make args array
for (x = 1; x < arguments.length; x++) {
args[args.length] = arguments[x];
}
//check whether function exist in local scope and not in global scope
if (typeof eval(fn) !== 'undefined' && typeof window[fn] === 'undefined') {
// ok, run the function
return eval(fn).apply(window, args);
}
else{
// log error if not found
loge('Singleton: function not found:' + fn);
return;
}
// the test fn accesses test2() without dot notation
function test(a) {
// Note: here in test fn it can access test2()
// without using this.test2() syntax
// as you would in normal objects
var s = test2();
alert(s + ' test:' + a);
};
function test2() {
return 'test2';
};
}
}
How about declaring functions that can access each other in separate closure, and exporting them to main method by binding your call method to an object containing the functions? Something like previous post (modified slightly):
var Singleton = {
call: (function() {
// here 'call' is bound to object containig your test functions
// this: {test, test2}
if (0 == arguments.length) return;
// log error if not found
if ('function' != typeof this[arguments[0]]) {
console.warn('Singleton: function not found:' + arguments[0]);
return;
}
// '...index into local scope and get function
// ie. get the function by it's name
return this[arguments[0]].
apply(window, Array.prototype.slice.call(arguments, 1));
// --- or:
// you can explicitly introduce function names to current scope,
// by `eval`-ing them here (not very much preferred way in JavaScript world):
for (var fname in this)
if (this.hasOwnProperty(fname))
eval('var ' + fname + ' = ' + this[fname]);
// and you can reference them directly by using their names
var fn = eval(arguments[0]);
return fn.apply(window, Array.prototype.slice.call(arguments, 1));
}).bind(
(function() {
var _exports = {};
function test (a) {
var s = test2();
alert(s + ' test: ' + a);
}
function test2 () {
return 'test2';
}
_exports['test'] = test;
_exports['test2'] = test2;
return _exports;
})()
)};
Singleton.call('test', 'foo and stuff');
//
previous post:
You are talking about Function#bind functionality that enables 'customizing' function's context. .bind() your call method to required 'local context' like this:
var Singleton = {
//main entry point
// call with fn name, args...
call: (function() {
// here `this` (context) is object bound to `call` method
// not `global` object, which is default for 'unbound' functions
var locals = this; // {fns, shift, loge, isfunc}
var fn;
var fun;
var x;
if (arguments.length == 0)
return;
// get the fn name
fn = locals.shift(arguments);
// '...index into local scope and get a fn'
fun = locals.fns[fn];
// log error if not found
if (!locals.isfunc(fun)) {
locals.loge('Singleton: function not found:' + fn);
return;
}
// ok, run the function
return fun.apply(window, arguments);
// lock `call`'s context to provided object
// and use `this` to reference it inside `call`
}).bind({
fns: (function(_) {
// and you can '...create a library of inter-dependent STATIC functions'
// in this closure and invoke them in `call` method above
_.test = function (a) {
var s = _.test2();
alert(s + ' test: ' + a);
};
_.test2 = function() {
return 'test2';
};
return _;
})({}),
// and create couple of helper methods as well...
isfunc: (function(_getclass) {
_getclass.func = _getclass(_getclass);
return ('function' !== typeof(/foo/)) ?
function(node) {
return 'function' == typeof node;
} :
function(node) {
return _getclass.func === _getclass(node);
};
})(Function.prototype.call.bind(Object.prototype.toString)),
loge: console.warn,
shift: Function.prototype.call.bind(Array.prototype.shift)
}),
};
Singleton.call('test', 'foo and stuff');
// eof
Here's one 'in your face answer', because I really don't like what I see here.
I don't see why you need this kind of construct, you already have that as part of language core.
1. dynamic lookup
you are doing it in a rather 'unprecedented' kind of way,
hashes already do that for you, and it's lightning fast to do a hash search.
If you are eval()-ing random strings to do simple name lookup you really have to
step aside from a keybord for a while... (no offense please)
2. closures
you are saying about 'using closures' which you actualy don't use.
your call function redeclares test functions each time it gets called,
and looks the ('fresh version') functions in it's own variable scope table,
instead of lookig them up in parent scope chains (aka. closures)
outside it's lexical location
3. nfe vs. nfd
ie. named function expressions vs. named function declarations
...you cannot assign a function to a local var and have it retain closure.
It is a feature, you might not be aware of how it works (it tripped me up as well).
check this article out for clarification
4. exceptions
Singleton: function name not found... x4!
Just go ahead and call a function,
interpreter will throw for you anyway if it cannot find/execute
5. eval (aka. ^^)
Singleton.call.ctx.fun = eval(Singleton.call.ctx.fn);
eval takes any string here(#!), and gladly executes ones like:
'for(;;);', or 'while(1);'... forever.
You probably don't want to have any code running unless it was your stuff.
6. arguments handling
It is considered best practice out there to use single (Object) options parameter
to 'fine tune' any significant piece of bundled functionality,
instead of trying to figure that out by type checking provided argument list
Here's, in couple of simple lines, what I (and as I can see #Jimmy Breck-McKye) suggest you should do:
var Singleton.call = (function () {
var funcmap = {
'f_1': function () {},
// etc.
'f_N': function () {},
};
return function (options) {
// options members:
// context, (Object) context, (defaults to global if none is given)
// func, (String) function_name,
// args, (Array) arguments to pass into a function
// this line does everything your 100+ lines long snippet was trying to:
// look's up parent scope for a function, tries to run it
// passing provided data, throws if it gets stuck.
return funcmap[options.func].apply(options.context, options.args);
};
})();
//
Answering my own question here.
The core of the issue is that you cannot assign a function to a local var and have it retain closure.
Consider that when writing a function with global and window scope, this is not necessary to call another function with identical scope. Such is not the case with member functions.
Another way of saying this is that there is no space where your cursor can sit and as you declare a function it automatically gets attached to the current this.
function fn(){}// if we are in global scope, then window.fn becomes defined
// but if we are inside, say, a constructor, simple declaration will not attach
// it to this, but fn is available in scope.
Any assignment on function declaration BREAKS part of the expected closure:
var IdentifierAvailableToClosure=function Unavailable(){}
But assignment after declaration works:
function NowAvailable(){}
var SynonymAvailableToo=NowAvailable;
This is what I meant by not wanting to repeat the name twice to get the mechanism to work.
This fact made me abandon other methods and rely on eval as suggested. Here is a first draft:
// This object is an encapsulation mechanism for a group of
// inter-dependent, static-ish, functions that can call each other
// without a this pointer prefix.
// Calls take the form of:
// Singleton.call(functionName:String [,arg1]...)
// or
// Singleton.call(contextObject:Object, functionName:String [,arg1]...)
// If a context is not provided, window is used.
//
// This type of mechanism is useful when you have defined a group
// of functions in the window/global scope and they are not ready
// to be formalized into a set of classes, or you have no intention
// of doing that
//
// To illustrate the issue, consider that a function
// which is defined in window/global scope
// does not have to use the this pointer to call a function of
// identical scope -- yet in a class member function, the this pointer
// MUST be used
// Therefore, trying to package such functions requires injecting
// the this pointer into function bodies where calls to associater
// functions are made
//
// Usage is primarily for development where one has control over
// global namespace pollution and the mechanism is useful in
// refactoring prior to formalization of methods into classes
var Singleton={
// Main call point
call:function(){
// Bail with error if no args
if (arguments.length==0) {
throw('Singleton: need at least 1 arg');
}
// As all functions in the local scope library below
// have access to the local scope via closure, we want to reduce
// pollution here, so lets attach locals to this call
// function instead of declaring locals
//
// Prepare to call anon fn
Singleton.call.args=arguments;
// Make ctx have args, context object, and function name
Singleton.call.ctx=(function (){// return args,ctx,name
// out
var args=[];
//locals
var x, fn;
// collapse identifier
var a=Singleton.call.args;
// closure object avail to functions, default to window
that=window;
// first real function argument
var arg_start=1;
// first arg must be function name or object
if (typeof a[0]=='string') {// use window ctx
fn=a[0];
// if first arg is object, second is name
}else if (typeof a[0]=='object') {
// assign given context
that=a[0];
// check second arg for string, function name
if (typeof a[1]!='string') {
var err='Singleton: second argument needs to be a fn name'
+' when first arg is a context object';
throw(err)
return;
}
// ok, have a name
fn=a[1];
// args follow
arg_start=2;
}else{
// improper arg types
var err='Singleton: first argument needs to be a string or object';
throw(err)
}
// build args array for function
for (x=arg_start;x<a.length;x++) {
args[args.length]=a[x];
}
// return context
return {
args: args
,that:that
,fn:fn
};
})();
// using function library present in local scope, try to find specified function
try{
Singleton.call.ctx.fun=eval(Singleton.call.ctx.fn);
}catch (e){
console.error('Singleton: function name not found:' + Singleton.call.ctx.fn);
throw('Singleton: function name not found:' + Singleton.call.ctx.fn);
}
// it must be a function
if (typeof Singleton.call.ctx.fun !== 'function') {
console.error('Singleton: function name not found:' + Singleton.call.ctx.fn);
throw('Singleton: function name not found:' + Singleton.call.ctx.fn);
}
// library functions use that instead of this
// that is visible to them due to closure
var that=Singleton.call.ctx.that;
// Do the call!
return Singleton.call.ctx.fun.apply(that, Singleton.call.ctx.args);
//
// cool library of functions below,
// functions see each other through closure and not through this.fn
function test(s){
alert(test2()+' test:'+s);
}
function info_props(){
console.info(this_props());
}
function test2(){
return 'test2';
}
function this_props(){
var s='';
for (var i in that) {
s+=' '+i;
}
return s;
};
}
};

Specifics of javascript cosntructors

Say I have a pure constructor function (containing nothing but this.Bar = bar)
1) When I call it from another function, can I pass the caller function's arguments directly when I call or must I do var myBar=new bar, myBar.Bar=thebar, where the bar is a caller argument?
2) Will the constructor still instantiate even if it doesn't get all the args?
3) How can I check if one of the args is unique, IE no other instance of the object has this value for the property in question? Specifically, I want to assign each object a unique index at creation. Maybe array?
Many thanks in advance
Say I have a pure constructor function (containing nothing but this.Bar = bar)
I'm going to assume you mean:
function MyConstructor(bar) {
this.Bar = bar;
}
(Note: The overwhelming convention in JavaScript is that property names start with a lower-case letter. So this.bar, not this.Bar. Initially-capped identifiers are usually reserved for constructor functions.)
1) When I call it from another function, can I pass the caller function's arguments directly when I call or must I do var myBar=new bar, myBar.Bar=thebar, where the bar is a caller argument?
You can pass them directly:
function foo(a, b, c) {
var obj = new MyConstructor(b);
}
2) Will the constructor still instantiate even if it doesn't get all the args?
The number of arguments passed is not checked by the JavaScript engine. Any formal arguments that you don't pass will have the value undefined when the function is called:
function MyConstructor(bar) {
console.log(bar);
}
var obj = new MyConstructor(); // logs "undefined"
3) How can I check if one of the args is unique, IE no other instance of the object has this value for the property in question? Specifically, I want to assign each object a unique index at creation. Maybe array?
In general, that's usually not in-scope for a constructor. But yes, you could use an array, or an object, to do that.
var knownBars = [];
function MyConstructor(bar) {
if (knownBars.indexOf(bar) !== -1) {
// This bar is known
}
else {
// Remember this bar
knownBars.push(bar);
}
}
Of course, indexOf may not be what you want for searching, so you may need to use some other method of Array.prototype or your own loop.
Another way would be to use an object; this assumes that bar is a string or something that can usefully be turned into a string:
var knownBars = {};
function MyConstructor(bar) {
if (knownBars.indexOf(bar) !== -1) {
// This bar is known
}
else {
// Remember this bar
knownBars[bar] = 1;
}
}
When I call it from another function, can I pass the caller function's arguments directly
There wouldn't be much point in having this.Bar = bar in the constructor function if you could not.
Will the constructor still instantiate even if it doesn't get all the args?
Assuming nothing inside it throws an exception if the argument is missing, yes. Arguments just get a value of undefined.
How can I check if one of the args is unique, IE no other instance of the object has this value for the property in question?
You'd need to have a shared store of them that you check against.
For example:
var Constructor = (function () {
var unique_check_store = {};
function RealConstructor(bar) {
if (typeof bar == 'undefined') {
throw "You must specify bar";
}
if (unique_check_store.hasOwnProperty(bar)) {
throw "You have already created one of these called '" + bar + "'";
}
this.Bar = bar;
unique_check_store[bar] = true;
}
return RealConstructor;
})();
var a, b, c;
try {
a = new Constructor();
} catch (e) {
alert(e);
}
try {
b = new Constructor("thing");
} catch (e) {
alert(e);
}
try {
c = new Constructor("thing");
} catch (e) {
alert(e);
}
alert(a);
alert(b);
alert(c);
​

Why methods lost from custom object on sendRequest()

I'm using simple custom type in content script of chrome extension. Array of items then sent to background page via chrome.extension.sendRequest(). In bgpage debugger shows that instances of my type don't have these methods. Also, the same happens with type properties with undefined values. What's wrong.
function User(id, holder) {
this.id = id;
var hObj = {};
hObj[holder] = 'undefined'; // this is ok
this.holder = hObj;
this.Result = undefined; // this will be lost
this.Code = undefined; // this will be lost
}
// this will be lost
User.prototype.getFirstHolderType = function() {
for (h in this.holder) {
if (h) return h;
}
return false;
};
// this will be lost
User.prototype.hasHolderType = function(h_type) {
for (h in this.holder) {
if (h_type === h) return true;
}
return false;
};
//...
chrome.extension.sendRequest({id: "users_come", users: users},
function(response) {});
Message passing uses JSON.stringify, which drops functions from objects when it stringifies them.
Why? A function is much more than just code -- it's a closure with loads of variable/scope information. If a function uses a global variable and the function gets move to a new execution environment, how should it behave? (In fact, the question is much for profound than "how should it behave?", it's more like "how could all of the variables in scope within the function be transported along with the function?".)
If you want to transport your function code (and know in advance that necessary variables will exist at the destination), you can use toString on your member functions to transport them a strings and use and eval to re-create them on arrival.
(JSON.stringify also drops members that have an undefined value. For example, JSON.stringify({"a":undefined}) yields "{}". If you want these values to be preserved, set them to null. A member variable set to undefined is indistinguishable from a member variable that was never set at all.)

Dynamically attach a function to grant access to private variables

I'm trying to assign a callback dynamically to an Object of mine, I can't seem to figure out a way to do this while granting this function access to private variables. I've listed the relavant code below with comments where I ran into walls.
Object Factory
function makeObj ( o ) {
function F() {}
F.prototype = o;
return new F();
}
Module
var MODULE = (function(){
var myMod = {},
privateVar = "I'm private";
return myMod;
})();
Various Attempts
myMod.someDynamicFunc = function someDynamicFunc(){
//privateVar === undefined;
alert( privateVar );
}
myMod.someDynamicFunc();
myMod.prototype.someDynamicFunc = function someDynamicFunc(){
//ERROR: Cannot set property 'someDynamicFunc' of undefined
alert(privateVar);
}
myMod.someDynamicFunc();
In this attempt I tried making a setter in the module object... to no avail.
var MODULE = (function(){
var myMod = {},
privateVar = "I'm private";
myMod.setDynamicFunction = function ( func ){
if(func !== undefined && typeof func === "function"){
//Uncaught TypeError:
// Cannot read property 'dynamicFunction' of undefined
myMod.prototype.dynamicFunction = func;
//also tried myMod.dynamicFunction = func;
}
}
return myMod;
})();
var myModule = makeObject( MODULE );
myModule.setDynamicFunction(function(){
alert(privateVar);
});
myModule.dynamicFunction();
Am I just using JavaScript wrong? I'd really like to be able to assign callbacks after the object is initiated. Is this possible?
You can't access the private variable via a callback function set dynamically (since it can't be a closure if it's attached later), but you can set up a system by which you would be able to access the variable:
var MODULE = (function(){
var myMod = {},
privateVar = "I'm private";
myMod.callback = function(fn) {fn(privateVar);};
return myMod;
})();
var someDynamicFunc = function(param) {alert(param);};
myMod.callback(someDynamicFunc);
Of course, this makes it not really private, since anyone could do this. I don't see how it would be possible at all for you to have a "private" variable that you access via dynamically attached functions, without allowing anyone else's dynamically attached functions to have the same privilege (thus making it not really private).
I guess you did not really understand exactly how closures work.
Closures mean that scopes always have access to the outer scope they were defined in.
function Counter(start) {
var count = start;
return {
increment: function() { // has access to the outer scope
count++;
},
get: function() {
return count;
}
}
}
var foo = new Counter(4);
foo.increment();
foo.get(); // 5
The above example returns two closures, both the function increment as well as get keep a reference to the count variable defined in the constructor.
One cannot access count from the outside, the only way to interact with it is via the two "closured" functions.
Remember, closures work by keeping a reference to their outer scopes, so the following does not work:
var foo = new Counter(4);
foo.hack = function() { // is not getting defined in the same scope that the original count was
count = 1337;
};
This will not change the variable count that's inside of Counter since foo.hack was not defined in that scope, instead, it will create or override the global variable count.

Categories