Syntax error when using `get` in object property shorthand - javascript

This bit of code:
function get() {
console.log('get')
}
var obj = {
get
}
obj.get()
results in a SyntaxError: Unexpected token } in iojs and Chrom{ium,e} but works fine in Firefox.
Longhand, of course, works fine:
function get() {
console.log('get')
}
var obj = {
get: get
}
obj.get()
So does using a word other than get
function git() {
console.log('get')
}
var obj = {
git
}
obj.git()
Is this a bug in V8 or something else? What am I not getting here?

v8 hasn't made this available by default yet1; firefox (which doesn't use v8) has.
For now, you can transpile with babel.js.
1 It's available, but not in every runtime environment. In node.js, for example, you need to enable it with a --harmony_something flag.

Related

Sentry on Internet Explorer 11

I'm using Sentry to log some errors on Javascript but while using Internet Explorer 11 I'm getting Syntax Error while configuring the scope
function addSentryTag(key, value) {
if (Sentry) {
Sentry.configureScope(scope => { scope.setTag(key, value);})
}
}
I assume the problem is using the lambda expression. Is there another way to add Tags to the scope?
I dont think IE11 supports the arrow syntax => are you running your code through any compilers like babel before trying it in the browser if not?
You can try this syntax:
function addSentryTag(key, value) {
if (Sentry) {
Sentry.configureScope(function(scope) {
scope.setTag(tag, value)
})
}
}
Give it a go :)
The same code without the lambda function:
function addSentryTag(key, value) {
if (Sentry) {
Sentry.configureScope(function(scope){
scope.setTag(key, value);
});
}
}

Detect if `scrollIntoView` accepts an object paramenter

The method element.scrollIntoView accepts one parameter. This parameter can be a boolean value or an object.
Currently, only Firefox supports the object syntax. I need to find a way to detect if the method allows an object to be passed.
The following is the code I'm trying to write:
var acceptsObjects = // part that I'm missing
if (acceptsObjects) {
element.scrollIntoView({ block: 'end', behavior: 'smooth' })
} else {
element.scrollIntoView(false)
}
My answer is quite late, but maybe it helps someone else:
function supportsScrollIntoViewOptions() {
var isSupported = false;
try {
var opts = {};
Object.defineProperty(opts, 'block', {
// define a getter on the opts object for the property 'block'
// if an object as the argument is supported, this function will be called and
// we can set `isSupported` to true
get: function() {
isSupported = true;
return 'nearest';
}
});
document.createElement('div').scrollIntoView(opts);
} catch(e) {}
return isSupported;
}
I have used var and old school method definitions for better backwards compatibility, as well as wrapped everything in a try { … } catch(e) { … }, which I’m not sure is necessary.
This was tested in Firefox 31.0, which returns false as well as Firefox 108.0.1 and Safari 15.5 which both return true. Even though Can I Use claims this feature is not supported in Safari 15.5 it works.
Please let me know if there are any improvements to my code.

Javascript: Basic for loop is not working

Is there any reason why the following would not work:
for (i=0;i < someArray.length;i++) {
if (someArray[i].indexOf("something") !== -1) {
//do something here
}
}
The most basic "for" loop possible. But it doesn't work. On the first line (declaration of the loop, not inside the loop), I get "Uncaught reference error; i is not defined."
I have this page open in one Chrome tab, and another earlier version of the page open in another tab. In the other tab, this loop works just fine; in the first tab, this code throws an error.
EDIT - July 2 2015
The response about strict mode was helpful. After reading up a bit and going through the code I've got a handle on what's going on.
The confusing bit was that both versions of the code look like this, with some minor differences (requirejs module):
define(
'viewModels/someViewModel',
['dependency1', 'dependency2', 'dependency3'],
function(dep1, dep2, dep3) {
"use strict";
function SomeViewModel(arg1, arg2) {
var self = this;
self.initialize();
self.removeRefinement = function(refinementString) {
var refinementArray = refinementString.split("&");
for (i=0;i < navigationArray.length;i++) { //<-- error
}
}
}
}
);
One version throws the reference error. One doesn't.
This is a large web application with many other pages and Javascript files. The only thing I could think of was that in one version of the code, maybe i had been inadvertently globally defined somewhere else in the app, where strict mode wasn't enabled. After running to the breakpoint and checking "window" I see that's exactly what's happening.
Thanks =D
If you are in strict mode, you'll get the error Uncaught reference error; i is not defined. If you're not in strict mode, you won't get the error.
This will throw the error
'use strict'
var someArray = ['aaa', 'bbb', 'ccc'];
for (i=0;i < someArray.length;i++) {
console.log(i)
if (someArray[i].indexOf("something") !== -1) {
//do something here
}
}
This won't
var someArray = ['aaa', 'bbb', 'ccc'];
for (i=0;i < someArray.length;i++) {
console.log(i)
if (someArray[i].indexOf("something") !== -1) {
//do something here
}
}
when you declare a variable it must be declared like this var i = 0;
a for loop looks like this:
JavaScript
for(var i = 0; i == 10; i++)
{
}

Initializing localStorage variables with Javascript doesn't work when in a function

Okay, so I'm using the following if statements to preset certain variables of an application I'm making:
if(localStorage.s1 == undefined) {
localStorage.s1= 50
}
if(localStorage.s2 == undefined) {
localStorage.s2= 100
}
And that works fine. There's about twelve of these presets, so I've re-factored it by using the following function:
function setterfunc(targetedelement, presetting) {
if(localStorage.targetedelement == undefined) {
localStorage.targetedelement = presetting;
}
}
But when I call it with
setterfunc(foobar, 342)
Google Chrome console just tells me:
Uncaught ReferenceError: foobar is not defined
Any help? The verbose way around of repeating the if statements works perfectly.
Use the bracket notation :
function setterfunc(targetedelement, presetting) {
if(localStorage[targetedelement] == undefined) {
localStorage[targetedelement] = presetting;
}
}
setterfunc('foobar', 342)
or the setItem and getItem accessors :
function setterfunc(targetedelement, presetting) {
if(localStorage.getItem(targetedelement) == undefined) {
localStorage.setItem(targetedelement) = presetting;
}
}
setterfunc('foobar', 342)
Side note : Be careful that localStorage only stores strings. So if you want to handle numbers, you'd better parse what you read from local storage.
The reason for the error is that the string foobar needs to be quoted, otherwise JS is looking for a variable of this name:
slidersetter('foobar', 342);
but your function is named setterfunc, not slidersetter.

JavaScript - Using object prototypes to extend the usage of a method?

I am very new to JavaScript, and when working with my object's prototype I try to call the current object to extend a method but it is not working. So I google'd my problem but didn't really get anywhere as it is practically impossible to phrase. However, I found the this keyword which I thought should work but didn't. Here's what I have:
(function( window, document, undefined ) {
var myObj = function ( ) { }; // not a noop
var ua = function() { return navigator.userAgent.toLowerCase(); }
function noop() { }; // empty noop function
myObj.prototype = {
constructor: myObj,
renderizr: {
presto: ua().match(/(opera|presto)/i),
trident: ua().match(/trident/i), // don't parse "msie" as opera uses this sometimes
webkit: ua().match(/(chrome|safari|webkit)/i),
gecko: ua().match(/(firefox|gecko)/i), // don't parse "netscape" as a lot of strings use this
val: '' // keep empty for now
}
};
// renderizr.val extension
// use this so the user can print the value of
// the rendering engine instead of using multiple
// conditional statements.
if(this.renderizr.presto) { this.renderizr.val = "Presto" }
else if(this.renderizr.trident) { this.renderizr.val = "Trident") }
else if(this.renderizr.webkit) { this.renderizr.val = "Webkit") }
else if(this.renderizr.gecko) { this.renderizr.val = "Gecko") }
window.myObj = new myObj();
}( window, document ));
This way, you can do alert(myObj.renderizr.val); instead of doing monotonous conditional statements.
I don't want to do generic browser name detection because you're only supposed to test for the features which you need, not the browser. However, some rendering engines have different habits for rendering web pages, so I do want to include engine detection in my script. (However, I don't suggest using this, like I said, I just want to get to know javascript and how it works, and it's not working!).
So my question is, what am I doing wrong here and how can I fix it? Why doesn't the this keyword work?
You are using this in a context where you are not in the instance of a myObj object. this will be the global scope (ie. window).
Also, all your code is running immediately, you are not defining any functions in your prototype.
I believe you want those checks inside your constructor:
var myObj = function () {
// renderizr.val extension
// use this so the user can print the value of
// the rendering engine instead of using multiple
// conditional statements.
if(this.renderizr.presto) { this.renderizr.val = "Presto" }
else if(this.renderizr.trident) { this.renderizr.val = "Trident" }
else if(this.renderizr.webkit) { this.renderizr.val = "Webkit" }
else if(this.renderizr.gecko) { this.renderizr.val = "Gecko" }
};
Also, you have some extra ) inside your else if statements, causing syntax errors. Check a working version here: http://jsfiddle.net/SnKSB/.

Categories