Pass an argument as a reference to get a JSON property - javascript

I'm working on a facebook app with JS SDK...
I want to create a function that makes an API call to the Graph API:
This is what I got:
function a(reference){
FB.api('/me', function(respond){
var it = respond.reference[0].name;
alert(it);
});
}
I try executing it this way but it doesn't work.
a("inspirational_people");

So you’re feeding the text string "inspirational_people" into your function, and you want to access a property of the response object having that very name?
That’s quite easy, basic JavaScript syntax: Every property that you can access via object.propertyName you can also access as object["propertyName"].
So in your case, since you want to access response.inspirational_people[0].name, it’s response[reference][0].name – the actual string value of reference is evaluated at runtime, and you should end up having what you wanted.

Related

Cannot set prototype of SpeechSynthesisVoice manually

This question is somewhat for understanding the prototype get-set.
I've a scenario where I need to map the SpeechSynthesis supported voice to Google Translation API supported language codes.
For example,
Now, I can do the same by either fetching the voices runtime or by storing the voice and hard-coding the mapping in some method in javascript.
If I go for runtime approach, I need to call getVoice() in speechSynthesis.onvoiceschanged = () => {} and then map the numbers, which gets called in every voice change event. So, I want to go for hard-coding one.
Now, when I store the mapping array in a variable and call it by index, I get the SpeechSynthesisVoice Object, just like what we do in getVoices()[index].
Further, If I set this object value to speechSynthesis.voice, I get an error:
Uncaught TypeError: Failed to set the 'voice' property on 'SpeechSynthesisUtterance': The provided value is not of type 'SpeechSynthesisVoice'.
This is due to mis-match of prototype of the manually stored object value.
For example,
1. SpeechSynthesisVoice object:
2. Manually stored value of SpeechSynthesisVoice object:
To resolve, this I've fetched the proto of the SpeechSynthesisVoice object using getVoice(), and then set it to a variable and further, set this variable to my manual mapped object.
Like,
Get:
voicePrototype = getVoices()[9].__proto__;
Set:
voices[index].SpeechSynthesisVoice.__proto__ = voicePrototype;
And, it gets set, as in below screenshot:
I've also tried through Object.setPrototypeOf() and got the same result.
Now, again when I want to set this object to speechSynthesis.voice, I still get the same error, although my prototype matches.
Can anyone, please advise, if its possible to set the object proto likewise and use it? Thanks in advance.

Does it make diffrence in speed efficiency of code if we assign property of object to another variable and then use it?

I wonder does it make difference if I use another variable to access the property of object once and for all or access the data that I want , from the object each time :
data = {position: [{X:12},{Y:4}] ,name : 'Smth'}
is there any diffrent between the following method :
const X = data.position[0].X
for(...){
...do somthing with X
}
or
for(...){
...do somthing with data.position[0].X
}
Yes, some different is exist. Every time when you call property js interpreter try to find calling property (or method) at prototype hierarchy.
Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk.
If you use variable to cache some data it will be faster than you use direct access.
There is some great benchmark to test it.

Shortcut for accessing object attributes in javascript

I have a model object with a property called definition that i am using across a class. I can access that property like model.attributes.definition
Every time that i want to use this property inside a method, and for the sake of clarity, i am creating a shortcut definition = model.attributes.definition at the very beggining so the method code does not get populated with boilerplate.
Because i am using it across several methods i thought that, instead of creating the shortcut on every method, i could create a little helper function to do the job:
getDefinition: (model) ->
model.attributes.definition
and then use it anywhere like
if getDefinition(model).name?
doSomething()
But aren't these function calls across my code innecessary/resource consuming for such a trivial task? What is a good approach in a situation like this?
You can also access object values via string:
definition = "attributes.definition"
then to access the value:
if model[definition].name?
doSomething()

Passing object from flex to javascript

I want to call a method in flex from javascript side,
so that I can retrieve javascript object which contains data in flex.
now I'm trying like
var result:Object = new Object()
var keyset:Array = data.getKeySet();
for (var i:int = 0 ; i < keyset.length ; i++) {
result[keyset[i]] = data.get(keyset[i]);
}
return result;
but it do not work. how can I make it right?
p.s. I know it is fundamental question, but I couldn't find anything even though I googled for an hour. So please help!
To communicate between Flash/Flex and JS on the page, use the ExternalInterface class. You can't directly pass objects, but you can convert your object into a serialisable/string. Here's how you'd call a function called 'myFunc' and set it two arguments, a string and a number:
ExternalInterface.call('myFunc',1,'aString');
After the function name, which must always be a string, there is a ...rest parameter. Simply enough, this means you can send any number of arguments to the function, separating them with commas (we do two here).
If you used AS2 at any point in the past you may know the 'eval' function, this was inherited from (and is thus still used by) JS - it analyses a string and attempts to parse it into JavaScript, using this you can literally send Javascript code instead of a func/args:
ExternalInterface.call('alert("Hello!")');
If you want two-way communication, use the ExternalInterface.addCallBack function to register a function as callable from JS.
In case of errors when doing this, you may need to adjust your embed code: "In the object tag for the SWF file in the containing HTML page, set the following parameter:
param name="allowScriptAccess" value="always"
I believe you cannot call a method in AS3 from JS directly (and vice-versa). There should be an interface for it though, where one can call the other. If i remember correctly, you should use the ExternalInterface API.
Also, you can't pass Flex objects to JS (and vice-versa) also. Try building a generic object that is serializable to JSON and use that serialized data in passing data to each other. The receiving party can parse it back to use the data. In this example, the code passed a string from JS to AS3.
In your case, the Flex function would:
build an object
stuff it with data
serialize it into a JSON string
return the string to the caller
Then when JS calls the function:
JS receives the string
Use JSON.parse() to reconstruct the JSON string into a JS object
use the object

How to get Javascript Objects from JavaScriptSerializer?

When I use the System.Web.Script.Serialization.JavaScriptSerializer.Serialize method, I get back valid JSON code.
This is usually perfect, but sometimes I want to get back the result as a Javascript object, not JSON. The Serialize method has an overload that takes a SerializationFormat parameter. That looks perfect... but it is marked as internal!
How can I get out a string of Javascript from the Serializer?
Take a look at the JScript DLL Eval object's JScriptEvaluate method (http://msdn.microsoft.com/en-us/library/microsoft.jscript.eval.jscriptevaluate.aspx):
using Microsoft.JScript;
var MyJSObject = Eval.JScriptEvaluate("{a:'Property1',b:'Property2'}", Engine);

Categories

Resources