Jump to content


Photo

General JavaScript


  • Please log in to reply
451 replies to this topic

#1 Jack

Jack

    NaN

  • Moderators
  • PipPipPipPipPip
  • 3,183 posts
  • Gender:Male
  • Location:Jersey Channel Islands
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 20 July 2015 - 10:54 AM

This thread is designed to talk about random JS topics, post relevant articles, and share ideas. Not every topic warrants its own thread, sometimes you just want to post a quick snippet or something you have seen.
 
I'll go first. Today I noticed you can label functions, loops and possibly other things in JS. Typically though you just use this in loops, I haven't come across a function example, but it doesn't error.

outer: 
for (i = 0; i < 10; i++) {
    console.log('donkey');
}

calculate_tips: 
function tips(x,y) {
    return x + y;
}

console.log(tips(1,5));

Has anyone seen this before? Or know what it is? I'm not sure what the repercussions of doing this would be, there's bound to be some. It's interesting anyway.



#2 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 20 July 2015 - 11:02 AM

Interesting, I'm not sure.  I don't see the benefit of doing this unless you can see the label in the browsers call stack?  I also rarely use loops now.  Tend to just stick with ES5 array methods like Map, ForEach, Reduce, Filter.  I think they are more descriptive of what they do :)

Here's some good videos on the higher order functions listed above 

 

I get the following warning from JSBin when I pasted in your example, but no compliants from the console so not sure what to make of it.

 1 warning

Line 7: Label 'calculate_tips' on function statement.
 
 
 

Edited by rbrtsmith, 20 July 2015 - 11:06 AM.


#3 Jack

Jack

    NaN

  • Moderators
  • PipPipPipPipPip
  • 3,183 posts
  • Gender:Male
  • Location:Jersey Channel Islands
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 20 July 2015 - 11:09 AM

 

Interesting, I'm not sure.  I get the following warning from JSBin

 1 warning

Line 7: Label 'calculate_tips' on function statement.

 

 

I was using a JS repl and it didn't error, but I guess it shouldn't be used with functions. I've seen it used with for loops before though. I guess the best bet for readability would simply be a single line comment.



#4 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 20 July 2015 - 11:45 AM

Does it have any advantages over a comment?  Suprised I haven't seen anybody mention these before (If they are useful)


Edited by rbrtsmith, 20 July 2015 - 11:45 AM.


#5 Jack

Jack

    NaN

  • Moderators
  • PipPipPipPipPip
  • 3,183 posts
  • Gender:Male
  • Location:Jersey Channel Islands
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 20 July 2015 - 11:48 AM

I've finally found out what it is https://developer.mo...tatements/label. Looking at this, my function example was massively incorrect, it's not used for that at all.



#6 Jack

Jack

    NaN

  • Moderators
  • PipPipPipPipPip
  • 3,183 posts
  • Gender:Male
  • Location:Jersey Channel Islands
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 21 July 2015 - 04:29 PM

Has anyone used React?

If so, does React use classes? I keep seeing this sort of code around, and didn't know if they were optional, or part of the framework.

class App extends React.Component {
  render() {
  }
}


#7 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 21 July 2015 - 07:58 PM

 

Has anyone used React?

If so, does React use classes? I keep seeing this sort of code around, and didn't know if they were optional, or part of the framework.

class App extends React.Component {
  render() {
  }
}

 

It's ES6 class syntax, pretty similar to how you can define methods on an object in ES6 - see below.

let foo = {
  render() {
    console.log('render');
  },
  
  add() {
    console.log('add');
  }
}

is equivalent to

var foo = {
  render: function render() {
    console.log('render');
  },

  add: function add() {
    console.log('add');
  }
};

The webpack/React combo I've been playing around with - the one used in the FEM course ships with the Babel ES6 transpiler so you can use pretty much all of the ES6 spec in your app - at least all the features I'm aware of and have tested.

https://babeljs.io/ -> click on the try it out tab :)

 

Talking of ES6 classes, a number of Big names have stated that they are a bad addition to the language and are there merely to appease Java developers / developers used to classical languages, when JavaScripts own prototypal system is the more powerful so it's totally unnecessary.  The devs who have stated this / something along these lines are: Kyle Simpson, Crockford, Eric Elliot.

See this tweet https://twitter.com/...934120252780544

 

Here's an example from Eric Elliott's gist of a React component creation without class, just using an object.

function PlainOldObjectComponent(props, context){
  var instance = Object.create(React.Component.prototype)

  instance.props = props
  instance.context = context
  instance.state = { message: 'Object literals ftw' }
  instance.render = function() {
    return <li>
     <button onClick={ e => this.setState({ message: 'stateful!' })}>
        {this.state.message}
      </button>
    </li>
  }

  return instance
}

Edited by rbrtsmith, 21 July 2015 - 08:05 PM.


#8 Jack

Jack

    NaN

  • Moderators
  • PipPipPipPipPip
  • 3,183 posts
  • Gender:Male
  • Location:Jersey Channel Islands
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 21 July 2015 - 08:21 PM

Talking of ES6 classes, a number of Big names have stated that they are a bad addition to the language and are there merely to appease Java developers / developers used to classical languages, when JavaScripts own prototypal system is the more powerful so it's totally unnecessary.  The devs who have stated this / something along these lines are: Kyle Simpson, Crockford, Eric Elliot.
See this tweet https://twitter.com/...934120252780544

 

That's the bit I was getting confused about, I thought you had to use classes in React. Thanks for clearing it up.

 

I've got a long way to go before working with frameworks like React (still trying to get better at vanilla JS), but I'm sure it will be worth it in the end.



#9 fleur

fleur

    Advanced Member

  • Members
  • PipPipPip
  • 379 posts
  • Gender:Female
  • Location:Moscow
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 21 July 2015 - 08:36 PM

So..ES6 decorators also a bad idea?

Btw: what does  it means - aka (sometimes i see a.k.a in MDN articles)?

 


#10 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 21 July 2015 - 08:41 PM

 

That's the bit I was getting confused about, I thought you had to use classes in React. Thanks for clearing it up.

 

I've got a long way to go before working with frameworks like React (still trying to get better at vanilla JS), but I'm sure it will be worth it in the end.

 

I think this is the way to go.  I've played around with React, but not built anything in great detail.  I feel like I've covered enough vanilla now, but I still know there's plenty of room for further improvement still - it seems never-ending especially now we've got ES6 to learn too.  I've set up Babel as a Grunt task in my projects just so I can add in bits of ES6 as I learn them, hopefully this will allow me to learn ES6 during work hours as well as in my spare time, kind of how I learn't Sass, first started off with nesting and variables, then some time later started to introduce mixins and so on.  I think it's an effective way to learn if you're struggling to find the time out of work.


Edited by rbrtsmith, 21 July 2015 - 08:43 PM.


#11 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 21 July 2015 - 08:45 PM

 

So..ES6 decorators also a bad idea?

Btw: what does  it means - aka (sometimes i see a.k.a in MDN articles)?

 

 

 

Haven't read up on them, but based on the intro from that article it seems they are just a way of declaring higher order functions, this has nothing to do with classes.  Higher order functions are one of the best features in JavaScript.  Classes are not, based on what the experts have been saying.


Edited by rbrtsmith, 21 July 2015 - 08:45 PM.


#12 Jack

Jack

    NaN

  • Moderators
  • PipPipPipPipPip
  • 3,183 posts
  • Gender:Male
  • Location:Jersey Channel Islands
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 21 July 2015 - 09:48 PM

As soon as I saw the JS videos with that Mattias guy, I knew who he was straight away.

He posts some really useful answers on Quora. I'd advise signing up if you haven't already. I've wasted hours reading some amazing answers to questions from professional developers, start-up founders, games developers, they are all on there. It's probably the only place you can get a legitimate long answer to a question from someone who either knows the industry, or worked on the project.

 

http://www.quora.com...hansson/answers



#13 Jack

Jack

    NaN

  • Moderators
  • PipPipPipPipPip
  • 3,183 posts
  • Gender:Male
  • Location:Jersey Channel Islands
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 22 July 2015 - 12:27 PM

Can anyone do a quick code review of this http://jsfiddle.net/...allot/jqaqs747/. It basically checks for SVG support and adds a class to the body. I'm not sure whether best practices are used here, I'm getting a bit confused in terms of when you use a function to call itself, when you assign one to a variable, ect.



#14 Lyndsey

Lyndsey

    Web Guru

  • Moderators
  • PipPipPipPipPip
  • 1,068 posts
  • Gender:Female
  • Location:South Wales
  • Experience:Intermediate
  • Area of Expertise:Web Developer

Posted 22 July 2015 - 02:02 PM

Can anyone do a quick code review of this http://jsfiddle.net/...allot/jqaqs747/. It basically checks for SVG support and adds a class to the body. I'm not sure whether best practices are used here, I'm getting a bit confused in terms of when you use a function to call itself, when you assign one to a variable, ect.

 

I'm not sure if there's an alternative method, but you can cut down your code slightly like so:

(function(){
    var checkSvg = function() {
      return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image", "1.1");
    }
    document.body.className+= (!checkSvg()) ? ' noSvg' : ' hasSvg';   
})(); 


#15 Jack

Jack

    NaN

  • Moderators
  • PipPipPipPipPip
  • 3,183 posts
  • Gender:Male
  • Location:Jersey Channel Islands
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 22 July 2015 - 02:18 PM

 

 

I'm not sure if there's an alternative method, but you can cut down your code slightly like so:

(function(){
    var checkSvg = function() {
      return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image", "1.1");
    }
    document.body.className+= (!checkSvg()) ? ' noSvg' : ' hasSvg';   
})(); 

 

I don't actually use the else statement, I just had it in there with an alert(); for testing on BrowserStack devices. I probably should have cleaned the code up a bit there. I'm guessing you can't use a ternary operator if you haven't included both a true and false value?

 

The bit that concerns me is if I'm using functions correctly.

 

Thanks for taking a look :)



#16 Jack

Jack

    NaN

  • Moderators
  • PipPipPipPipPip
  • 3,183 posts
  • Gender:Male
  • Location:Jersey Channel Islands
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 30 July 2015 - 10:39 AM

I've been messing around with the Wordpress API and Handlebars JS.

 

It's quite nifty when you combine the two. You can have WP providing the data and you can completely disconnect the front-end.

 

I'm going to do some more digging into it, but it seems like a more modern approach to building themes. You can use whatever framework you want too, because it's just JSON. At the moment I have jQuery fetching the data, and Handlebars does the templating (variables, conditionals, loops).



#17 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 30 July 2015 - 11:03 AM

I've been messing around with the Wordpress API and Handlebars JS.

 

It's quite nifty when you combine the two. You can have WP providing the data and you can completely disconnect the front-end.

 

I'm going to do some more digging into it, but it seems like a more modern approach to building themes. You can use whatever framework you want too, because it's just JSON. At the moment I have jQuery fetching the data, and Handlebars does the templating (variables, conditionals, loops).

 

 

Sounds good :)  you have a link to any articles regarding this?


Edited by rbrtsmith, 30 July 2015 - 11:04 AM.


#18 Jack

Jack

    NaN

  • Moderators
  • PipPipPipPipPip
  • 3,183 posts
  • Gender:Male
  • Location:Jersey Channel Islands
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 30 July 2015 - 12:18 PM

 

 

Sounds good :)  you have a link to any articles regarding this?

 

http://wp-api.org/

 

http://wordpress.tv/...ss-in-the-back/

 

http://www.tutorials...-response.html/



#19 Jack

Jack

    NaN

  • Moderators
  • PipPipPipPipPip
  • 3,183 posts
  • Gender:Male
  • Location:Jersey Channel Islands
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 30 July 2015 - 01:59 PM

@rbrtsmith I've been pretty busy this week, but I should have time next week to run through Craft on Slack, if you're still interested.



#20 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 30 July 2015 - 02:02 PM

@rbrtsmith I've been pretty busy this week, but I should have time next week to run through Craft on Slack, if you're still interested.

 

Sure, few guys at my place are interested too.  When is good for you?



#21 Jack

Jack

    NaN

  • Moderators
  • PipPipPipPipPip
  • 3,183 posts
  • Gender:Male
  • Location:Jersey Channel Islands
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 30 July 2015 - 02:07 PM

Wednesday (5th) is probably best, around 7:30.

 

Are you using more than one account? If so, those accounts will need inviting in beforehand.

 

I'd also spin a demo up before too https://demo.buildwithcraft.com/.


Edited by Jack, 30 July 2015 - 02:08 PM.


#22 fleur

fleur

    Advanced Member

  • Members
  • PipPipPip
  • 379 posts
  • Gender:Female
  • Location:Moscow
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 31 July 2015 - 09:45 PM

I was playing with prototype and tried to understand how it works in real situation. I tried to create prototype for span and then loop all spans and change color. But it seems to me that i missed the to main things. I lost 'this' and 'argument object'.  If anyone can point me to the right directions i will be very greatful. Is this code really make sense in production? All tests for junior devs include prototype knowledge. But i wonder maybe it's better to use module pattern or factory function for this goals? I need advice about code structure. Maybe for this it's better to use object, properties and metods and share prototype via object.create(). Or just write a simple function with one argument? I am a little confused about this.

 

DEMO

<main>
<span class="test">classN</span>
<span class="test">classN</span>
<span class="test">classN</span>
</main>
function colorWrapper(color) {
    function addColor {
        this.targetElem = color;
        this.coloredElem = function(args) {
        this.targetElem.style.color = args;   
       };
        this.listen = function(args) {
            this.targetElem.addEventListener('click', function(e) {
               this.coloredElem(args);
            }.bind(this), false);
            };

        return this;
    }
    
    return new addColor(color);
}

var test = document.getElementsByClassName('test');
// implement

for(var i = 0; i < test.length; i++) {
    var coloredEl = colorWrapper(test);
    coloredEl.listen('green');
}




Edited by fleur, 31 July 2015 - 10:59 PM.


#23 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 01 August 2015 - 10:39 AM

Wednesday (5th) is probably best, around 7:30.

 

Are you using more than one account? If so, those accounts will need inviting in beforehand.

 

I'd also spin a demo up before too https://demo.buildwithcraft.com/.

Will get back to you when my collegues ok it.



#24 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 01 August 2015 - 10:44 AM

 

I was playing with prototype and tried to understand how it works in real situation. I tried to create prototype for span and then loop all spans and change color. But it seems to me that i missed the to main things. I lost 'this' and 'argument object'.  If anyone can point me to the right directions i will be very greatful. Is this code really make sense in production? All tests for junior devs include prototype knowledge. But i wonder maybe it's better to use module pattern or factory function for this goals? I need advice about code structure. Maybe for this it's better to use object, properties and metods and share prototype via object.create(). Or just write a simple function with one argument? I am a little confused about this.

 

DEMO

<main>
<span class="test">classN</span>
<span class="test">classN</span>
<span class="test">classN</span>
</main>
function colorWrapper(color) {
    function addColor {
        this.targetElem = color;
        this.coloredElem = function(args) {
        this.targetElem.style.color = args;   
       };
        this.listen = function(args) {
            this.targetElem.addEventListener('click', function(e) {
               this.coloredElem(args);
            }.bind(this), false);
            };

        return this;
    }
    
    return new addColor(color);
}

var test = document.getElementsByClassName('test');
// implement

for(var i = 0; i < test.length; i++) {
    var coloredEl = colorWrapper(test);
    coloredEl.listen('green');
}



 

Not sure what you mean by prototype here.. in JS we have prototypal inheritance but nothing in your code is really demonstrating anything to do with that.  an example of prototypal inheritance is say calling .toString() on an Array.  - The array prototype does not have the method toString, so it looks further up the chain - next up is the Object prototype, where it will find the method.

 

Factory functions are better for object creation than constructors, you don't have to worry about the new keyword etc.  But that's just object creation, you can always add a prototype to that object that other objects can link to.

In JS try to think of it like objects linking to other objects rather than classes.



#25 fleur

fleur

    Advanced Member

  • Members
  • PipPipPip
  • 379 posts
  • Gender:Female
  • Location:Moscow
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 01 August 2015 - 03:19 PM

Thank you! I think i understand now. I tried to understand how to pass arguments in addEvenetListener function and keep this arguments in methods inside construction. But didn't understand how to do this right way. Using anonymous function i can't remove eventlistener.   I found this post.  But now i see that it's maybe old way. And constructor is not good. Okey.. i will play with factory functions. :) I think that learn about right code structure is the most important thing


Edited by fleur, 01 August 2015 - 03:21 PM.


#26 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 01 August 2015 - 03:40 PM

I recommend when trying to learn native JavaScript functionality to avoid doing anything with the DOM, addEventListener isn't a part of JavaScript, it is a part of the DOM API that you are merely referencing through JavaScript.  You'll find the courses that are teaching general JavaScript on CodeSchool and Frontend Masters don't cover the DOM at all unless they specifically say so in the course name, they mostly focus on the language itself and have specific courses for the DOM API / Frameworks.

 

For my learning I just work with data and output things to the console.  It's pretty rare that I use prototypes anyway, and even rarer that I use the for anything DOM related.


Edited by rbrtsmith, 01 August 2015 - 03:41 PM.


#27 fleur

fleur

    Advanced Member

  • Members
  • PipPipPip
  • 379 posts
  • Gender:Female
  • Location:Moscow
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 01 August 2015 - 03:49 PM

I see. But how i can create code without triggering DOM? Maybe you mean that every framework has it's own DOM spec, like jq or Angular. How i can pass element without DOM knowledge? And in all tests i see that i have to use native js DOM or use angular. I am confused. So. If no prototype every time i should create the same code for different objects?



#28 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 01 August 2015 - 04:21 PM

Look on the courses I mentioned.

 

Just output results of things to the console via console.log()

 

Not everything with JavaScript is Dom, The browser is one of many places it lives.  There's no DOM in Node for example.

 

I'm not saying don't use the DOM in your UI's, I'm talking purely for learning things like prototypes etc, just use the language and nothing else.



#29 fleur

fleur

    Advanced Member

  • Members
  • PipPipPip
  • 379 posts
  • Gender:Female
  • Location:Moscow
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 01 August 2015 - 04:46 PM

I think, now i understand, thank you!



#30 fleur

fleur

    Advanced Member

  • Members
  • PipPipPip
  • 379 posts
  • Gender:Female
  • Location:Moscow
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 01 August 2015 - 08:43 PM

I wonder is this factory function really userful and where i can use it?

function Address (param) {
  var self = {};
 
  if (param === 'dev'){
    self = {
      state: ‘Colorado’,
      saveToLog: function(){
        // write info to a log file
      }
    };
  } else {
    self = {
      state: 'Colorado'
    };
  }
 
  return self;
}
 
var devAddress = Address('dev');
console.log(devAddress.state);
var productionAddress = Address();

When i try to use it like so:

console.log(devAddress.state);

it shows an error, but why?


Edited by fleur, 01 August 2015 - 08:44 PM.


#31 Nillervision

Nillervision

    All-rounder

  • Privileged
  • PipPipPipPipPip
  • 1,593 posts
  • Gender:Male
  • Location:Copenhagen, Denmark
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 02 August 2015 - 08:57 AM

I wonder is this factory function really userful and where i can use it?

function Address (param) {
  var self = {};
 
  if (param === 'dev'){
    self = {
      state: ‘Colorado’,
      saveToLog: function(){
        // write info to a log file
      }
    };
  } else {
    self = {
      state: 'Colorado'
    };
  }
 
  return self;
}
 
var devAddress = Address('dev');
console.log(devAddress.state);
var productionAddress = Address();

When i try to use it like so:

console.log(devAddress.state);

it shows an error, but why?

The quotes are wrong in your if clause:

state: ‘Colorado’

should be

state: 'Colorado'

Use " " or ' ' instead of ‘ ’ (can be hard to see with some fonts)


Edited by Nillervision, 02 August 2015 - 09:03 AM.


#32 Nillervision

Nillervision

    All-rounder

  • Privileged
  • PipPipPipPipPip
  • 1,593 posts
  • Gender:Male
  • Location:Copenhagen, Denmark
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 02 August 2015 - 09:06 AM

Can anyone do a quick code review of this http://jsfiddle.net/...allot/jqaqs747/. It basically checks for SVG support and adds a class to the body. I'm not sure whether best practices are used here, I'm getting a bit confused in terms of when you use a function to call itself, when you assign one to a variable, ect.

 

I'm not sure if there's an alternative method, but you can cut down your code slightly like so:

(function(){
    var checkSvg = function() {
      return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image", "1.1");
    }
    document.body.className+= (!checkSvg()) ? ' noSvg' : ' hasSvg';   
})(); 

 

Here is the most simple SVG check I have seen:
 

if (typeof SVGRect != "undefined") { /* The browser supports SVG */ }
else { /* The browser does not support SVG */ }

(James Donnellys answer here: http://stackoverflow...method-is-best)

Now that we are at it: How do you guys check for audio/video support?
I found that the best way is to check if the canPlayType method is implemented...
 

var audio = document.createElement('audio');
//check if the canPlayType method is supported the !! converts the method to a boolean
var audioTagSupport = !!audio.canPlayType;
if (audioTagSupport == true){
    //The browser does support HTML5-audio
    //Moving on to check what mimetypes are supported
    if(audio.canPlayType("audio/mp3")){ /* The browser can play mp3 */}
    else{ /* The browser can not play mp3 */}
}
else{
    //The browser does not support HTML5-audio
}

Edited by Nillervision, 02 August 2015 - 09:07 AM.


#33 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 02 August 2015 - 09:27 AM

The quotes are wrong in your if clause:

state: ‘Colorado’

should be

state: 'Colorado'

Use " " or ' ' instead of ‘ ’ (can be hard to see with some fonts)

 

Well spotted.  I should also add in Fleurs that the variable self was declared as an empty object literal, there's no need to reassign it another object so the code could be optimised to become

function address (param) {
  var obj = {};
 
  if (param === 'dev'){
    obj.state = 'Colorado';
    obj.saveToLog = function(){
        // write info to a log file
    };
  } else {
    obj.state = 'Colorado';
  }
 
  return obj;
}

Also you should not capitalise the first letter of your function, doing so will make authors assume that it's a constructor (That's a best practice if you are defining constructors as they HAVE to be called with the 'new' keyword otherwise you end up with a load of globals)  This function isn't a constructor, it's a factory because it returns an object and doesn't require the use of 'this'.

With that in mind, the name self is generally used to refer to the 'this' value for use in nested inner scopes as 'this' isn't bound lexically and therefore not accessible to inner scopes, we bind it's value to a variable that is accessible.  So I also wouldn't use self as the name here either.

 

Here's an example of how self works

var outer = function() {
  var self = this.bam,
      inner;
  console.log('Outer this: ' + this.bam);  // 'Hello this is bam' - this is bound to the calling object - foo.
  inner = function() {
    console.log('Inner this: ' + this.bam); // undefined - now this points to the global object that has no property bam
    console.log('self: ' + self); // 'Hello this is bam' - self was bound in the outer scope to that scopes this value.
  };
  inner();
};

var foo = {
  bar : outer,
  bam : 'hello this is bam'
};

foo.bar();

Edited by rbrtsmith, 02 August 2015 - 09:42 AM.


#34 fleur

fleur

    Advanced Member

  • Members
  • PipPipPip
  • 379 posts
  • Gender:Female
  • Location:Moscow
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 02 August 2015 - 10:26 AM

Thank you alot for all explanations! I couldn't only understand one thing. Can i use this factory pattern to define extra metod, like in constructor? It's not comfortable every time to change the address function if needed. (For instance if i have many buttons and i need to correct behavior of a few of them).

 

I tried this, but method don't working like in normal constructor:

address.prototype.myMetod = function(state) {
   return obj.state = state;
}

var devAddress = address("dev");
console.log(devAddress.state); //working

var productionAddress = address();
console.log(productionAddress.state); //working

console.log(devAddress.myMetod("Taiti")); //doesn't work

Edited by fleur, 02 August 2015 - 10:27 AM.


#35 fleur

fleur

    Advanced Member

  • Members
  • PipPipPip
  • 379 posts
  • Gender:Female
  • Location:Moscow
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 02 August 2015 - 10:50 AM

var outer = function() {
var self = this.bam,
inner;
console.log('Outer this: ' + this.bam); // 'Hello this is bam' - this is bound to the calling object - foo.
inner = function() {
console.log('Inner this: ' + this.bam); // undefined - now this points to the global object that has no property bam
console.log('self: ' + self); // 'Hello this is bam' - self was bound in the outer scope to that scopes this value.
};
inner();
};

var foo = {
bar : outer,
bam : 'hello this is bam'
};

foo.bar();

 

 

Really Great construction! Thank you very much for share. Now i fully understand 'this'.



#36 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 02 August 2015 - 11:00 AM

 

Really Great construction! Thank you very much for share. Now i fully understand 'this'.

 

There's more to 'this' than what I posted, Kyle Simpson covers it in extreme detail in his You Don't Know JS book series.

 

in short 'this' binding is dependent upon the call site of the function, it has nothing to do with where the function itself lives.

 

  1. standard function call - 'this' is bound to the global object, in a browser that is the 'window'
  2. as a method call - 'this' is bound to the object that the called method resides in.
  3. a constructor - 'this' is bound to the newly created object, constructor called with 'new' keyword.
  4. .call, .apply and .bind - 'this' will be bound to whatever you pass into those functions as the first parameter.

As for which one wins out -  it goes in order of precedence - #4 will always win out over #1 for example.

 

In ES6 arrow functions 'this' is bound slightly differently and I'm still working on getting my head fully round it, for the time being I only use arrow functions when I'm not referencing 'this' until I properly understand how the mechanism works - but beware it does not follow the pattern above.


Edited by rbrtsmith, 02 August 2015 - 11:04 AM.


#37 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 02 August 2015 - 11:16 AM

 

Thank you alot for all explanations! I couldn't only understand one thing. Can i use this factory pattern to define extra metod, like in constructor? It's not comfortable every time to change the address function if needed. (For instance if i have many buttons and i need to correct behavior of a few of them).

 

I tried this, but method don't working like in normal constructor:

address.prototype.myMetod = function(state) {
   return obj.state = state;
}

var devAddress = address("dev");
console.log(devAddress.state); //working

var productionAddress = address();
console.log(productionAddress.state); //working

console.log(devAddress.myMetod("Taiti")); //doesn't work

Why are you returning something thats just been re-assigned (line 2) just return one or the other.  your function right now is just returning the state parameter.


Edited by rbrtsmith, 02 August 2015 - 11:17 AM.


#38 fleur

fleur

    Advanced Member

  • Members
  • PipPipPip
  • 379 posts
  • Gender:Female
  • Location:Moscow
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 02 August 2015 - 01:58 PM

I wanted to create method, where i can pass argument and create, for instance, different colors or background for buttons. I wonder, if i have buttons for different goals and these buttons have different behavior. I want to create different methods for different buttons (prototype) and  pass argument in each method, like so:

address.prototype.myMetod = function(arg) {
   obj.style.background = "gray"; // for non active buttons, for instance 
}

it's wrong constructions, of cause. I try to understand how i can share methods between instance of factory functions and when call it:

address.prototype.myMetod = function() {
   // my  method here
}

Maybe with factory i can't create prototype methods?

 

Thank you for explanation of call, .apply and .bind. I was really confused about this for a long time.


Edited by fleur, 02 August 2015 - 01:59 PM.


#39 rbrtsmith

rbrtsmith

    ReferenceError

  • Privileged
  • PipPipPipPipPip
  • 4,016 posts
  • Gender:Male
  • Location:Manchester, UK
  • Experience:Nothing
  • Area of Expertise:Web Developer

Posted 02 August 2015 - 02:48 PM

For now just create a new object for each button, inheritance is just there to save on memory, and really unless you're creating tens of hundreds it really isn't necessary.

 

In your example you're trying to add a prototype to the factory function itself rather than the objects it creates.  Why not add the method inside of the factory so that it attaches to each object, you don't need prototypes for this.

function address (param) {
  var obj = {};
 
  if (param === 'dev'){
    obj.state = 'Colorado';
    obj.saveToLog = function(){
        // write info to a log file
    };
  } else {
    obj.state = 'Colorado';
  }
  
  obj.myMethod = function() {
    // do stuff
  };

 
  return obj;
}

Edited by rbrtsmith, 02 August 2015 - 02:48 PM.


#40 fleur

fleur

    Advanced Member

  • Members
  • PipPipPip
  • 379 posts
  • Gender:Female
  • Location:Moscow
  • Experience:Advanced
  • Area of Expertise:Web Designer

Posted 02 August 2015 - 10:59 PM

Thank you a lot! I think i will keep in mind prototype only for my knowledge. I will play more times with call, apply, bind, var outer and var foo above. I feel, that i will need this constructions very often. It was very informative day, indeed:)






2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users