Rectangle 27 22

Unicode in Javascript Regexen

Like Java itself, Javascript doesn't support Unicode in its \w, \d, and \b regex shortcuts. This is (arguably) a bug in Java and Javascript. Even if one manages through casuistry or obstinacy to argue that it is not a bug, it's sure a big gotcha. Kinda bites, really.

The problem is that those popular regex shortcuts only apply to 7-bit ASCII whether in Java or in Javascript. This restriction is painfully 1970sish; it makes absolutely no sense in the 21 century. This blog posting from this past March makes a good argument for fixing this problem in Javascript.

It would be really nice if some public-spirited soul would please add Javascript to this Wikipedia page that compares the support regex features in various languages.

This page says that Javascript doesn't support any Unicode properties at all. That same site has a table that's a lot more detailed than the Wikipedia page I mention above. For Javascript features, look under its ECMA column.

However, that table is in some cases at least five years out of date, so I can't completely vouch for it. It's a good start, though.

Ruby, Python, Perl, and PCRE all offer ways to extend \w to mean what it is supposed to mean, but the two Jthingies do not.

In Java, however, there is a good workaround available. There, you can use \pL to mean any character that has the Unicode General_Category=Letter property. That means you can always emulate a proper \w using [\pL\p{Nd}_].

Indeed, there's even an advantage to writing it that way, because it keeps you aware that you're adding decimal numbers and the underscore character to the character class. With a simple \w, please sometimes forget this is going on.

I don't believe that this workaround is available in Javascript, though. You can also use Unicode properties like those in Perl and PCRE, and in Ruby 1.9, but not in Python.

The only Unicode properties current Java supports are the one- and two-character general properties like \pN and \p{Lu} and the block properties like \p{InAncientSymbols}, but not scripts like \p{IsGreek}, etc.

The future JDK7 will finally get around to adding scripts. Even then Java still won't support most of the Unicode properties, though, not even critical ones like \p{WhiteSpace} or handy ones like \p{Dash} and \p{Quotation_Mark}.

SIGH! To understand just how limited Java's property support is, merely compare it with Perl. Perl supports 1633 Unicode properties as of 2007's 5.10 release, and 2478 of them as of this year's 5.12 release. I haven't counted them for ancient releases, but Perl started supporting Unicode properties back during the last millennium.

Lame as Java is, it's still better than Javascript, because Javascript doesn't support any Unicode properties whatsoCENSOREDever. I'm afraid that Javascript's paltry 7-bit mindset makes it pretty close to unusable for Unicode. This is a tremendously huge gaping hole in the language that's extremely difficult to account for given its target domain.

javascript - Why this regex is not working for german words? - Stack O...

javascript jquery regex unicode
Rectangle 27 151

1- How JavaScript functions actually work:

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Person

do the same exact thing without using prototype and new keyword

So in this step functions, objects and this keyword, are all we have.

this
new
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

Person("George");
getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.Person("George");
person.getName();// -->"George"
person
Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName
};

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

as you see using any of these two way this would exactly point to the person object.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

and

The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:

Person.call(person, "George");
//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

var newObject = {};

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
getName
my_person_prototype
newObject.getName();

we can do this with our sample like:

Person.call(newObject, "George");
Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

console.log(Object.prototype.__proto__===null);//true

and that's how inheritance works in JavaScript.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

+1 for the illustration at the end of your "book" :)

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 147

1- How JavaScript functions actually work:

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Person

do the same exact thing without using prototype and new keyword

So in this step functions, objects and this keyword, are all we have.

this
new
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

Person("George");
getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.Person("George");
person.getName();// -->"George"
person
Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName
};

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

as you see using any of these two way this would exactly point to the person object.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

and

The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:

Person.call(person, "George");
//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

var newObject = {};

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
getName
my_person_prototype
newObject.getName();

we can do this with our sample like:

Person.call(newObject, "George");
Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

console.log(Object.prototype.__proto__===null);//true

and that's how inheritance works in JavaScript.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

+1 for the illustration at the end of your "book" :)

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 147

1- How JavaScript functions actually work:

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Person

do the same exact thing without using prototype and new keyword

So in this step functions, objects and this keyword, are all we have.

this
new
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

Person("George");
getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.Person("George");
person.getName();// -->"George"
person
Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName
};

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

as you see using any of these two way this would exactly point to the person object.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

and

The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:

Person.call(person, "George");
//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

var newObject = {};

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
getName
my_person_prototype
newObject.getName();

we can do this with our sample like:

Person.call(newObject, "George");
Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

console.log(Object.prototype.__proto__===null);//true

and that's how inheritance works in JavaScript.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

+1 for the illustration at the end of your "book" :)

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 147

1- How JavaScript functions actually work:

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Person

do the same exact thing without using prototype and new keyword

So in this step functions, objects and this keyword, are all we have.

this
new
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

Person("George");
getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.Person("George");
person.getName();// -->"George"
person
Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName
};

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

as you see using any of these two way this would exactly point to the person object.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

and

The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:

Person.call(person, "George");
//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

var newObject = {};

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
getName
my_person_prototype
newObject.getName();

we can do this with our sample like:

Person.call(newObject, "George");
Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

console.log(Object.prototype.__proto__===null);//true

and that's how inheritance works in JavaScript.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

+1 for the illustration at the end of your "book" :)

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 10

What kind of JavaScript syntax is this.

Anything starting with a // is a Javascript comment.

Sprockets on the server side scans the JS file for directives. //= is a special Sprocket directive. When it encounters that directive it asks the Directive Processor to process the command, require in this example. In the absence of Sprockets the //= require .. line would be a simple JS comment.

Usually, you want to concatenate all your app JS files and then minify them into 1 master JS file and then include that. I recommend reading the YSlow best practices on this.

Thanks a lot for the detailed answer and the video link, too.

javascript - Ruby on Rails - how require is executed in application.js...

javascript jquery ruby-on-rails jquery-ui require
Rectangle 27 98

JavaScript does not have block scope. Variables introduced with a bloc...

Bit late to the party, but I was exploring this issue today and noticed that many of the answers don't completely address how Javascript treats scopes, which is essentially what this boils down to.

So as many others mentioned, the problem is that the inner function is referencing the same i variable. So why don't we just create a new local variable each iteration, and have the inner function reference that instead?

Just like before, where each inner function outputted the last value assigned to i, now each inner function just outputs the last value assigned to ilocal. But shouldn't each iteration have it's own ilocal?

Turns out, that's the issue. Each iteration is sharing the same scope, so every iteration after the first is just overwriting ilocal. From MDN:

Important: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.

We can see this by checking ilocal before we declare it in each iteration:

This is exactly why this bug is so tricky. Even though you are redeclaring a variable, Javascript won't throw an error, and JSLint won't even throw a warning. This is also why the best way to solve this is to take advantage of closures, which is essentially the idea that in Javascript, inner functions have access to outer variables because inner scopes "enclose" outer scopes.

This also means that inner functions "hold onto" outer variables and keep them alive, even if the outer function returns. To utilize this, we create and call a wrapper function purely to make a new scope, declare ilocal in the new scope, and return an inner function that uses ilocal (more explanation below):

Creating the inner function inside a wrapper function gives the inner function a private environment that only it can access, a "closure". Thus, every time we call the wrapper function we create a new inner function with it's own separate environment, ensuring that the ilocal variables don't collide and overwrite each other. A few minor optimizations gives the final answer that many other SO users gave:

//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '<p>' + msg + '</p>';};

var funcs = {};
for (var i = 0; i < 3; i++) {
    funcs[i] = wrapper(i);
}
for (var j = 0; j < 3; j++) {
    funcs[j]();
}
//creates a separate environment for the inner function
function wrapper(ilocal) {
    return function() { //return the inner function
        console.log("My value: " + ilocal);
    };
}

I like how you explained the IIFE way as well. I was looking for that. Thank you.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 98

JavaScript does not have block scope. Variables introduced with a bloc...

Bit late to the party, but I was exploring this issue today and noticed that many of the answers don't completely address how Javascript treats scopes, which is essentially what this boils down to.

So as many others mentioned, the problem is that the inner function is referencing the same i variable. So why don't we just create a new local variable each iteration, and have the inner function reference that instead?

Just like before, where each inner function outputted the last value assigned to i, now each inner function just outputs the last value assigned to ilocal. But shouldn't each iteration have it's own ilocal?

Turns out, that's the issue. Each iteration is sharing the same scope, so every iteration after the first is just overwriting ilocal. From MDN:

Important: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.

We can see this by checking ilocal before we declare it in each iteration:

This is exactly why this bug is so tricky. Even though you are redeclaring a variable, Javascript won't throw an error, and JSLint won't even throw a warning. This is also why the best way to solve this is to take advantage of closures, which is essentially the idea that in Javascript, inner functions have access to outer variables because inner scopes "enclose" outer scopes.

This also means that inner functions "hold onto" outer variables and keep them alive, even if the outer function returns. To utilize this, we create and call a wrapper function purely to make a new scope, declare ilocal in the new scope, and return an inner function that uses ilocal (more explanation below):

Creating the inner function inside a wrapper function gives the inner function a private environment that only it can access, a "closure". Thus, every time we call the wrapper function we create a new inner function with it's own separate environment, ensuring that the ilocal variables don't collide and overwrite each other. A few minor optimizations gives the final answer that many other SO users gave:

//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '<p>' + msg + '</p>';};

var funcs = {};
for (var i = 0; i < 3; i++) {
    funcs[i] = wrapper(i);
}
for (var j = 0; j < 3; j++) {
    funcs[j]();
}
//creates a separate environment for the inner function
function wrapper(ilocal) {
    return function() { //return the inner function
        console.log("My value: " + ilocal);
    };
}

I like how you explained the IIFE way as well. I was looking for that. Thank you.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 115

Simpler with Node.js

JavaScript uses prototypes and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.

Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; when a function is called as a method of an object, the function's local this keyword is bound to that object for that invocation.

var MyObject = (function () {

    // Constructor
    function MyObject (foo) {
        this._foo = foo;
    }

    function privateFun (prefix) {
        return prefix + this._foo;
    }

    MyObject.prototype.publicFun = function () {
        return privateFun.call(this, '>>');
    }

    return MyObject;
})();


var myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined

The call function allows us to call the private function with the appropriate context (this).

If you are using node.js, you don't need the IIFE because you can take advantage of the module loading system:

function MyObject (foo) {
    this._foo = foo;
}

function privateFun (prefix) {
    return prefix + this._foo;
}

MyObject.prototype.publicFun = function () {
    return privateFun.call(this, '>>');
}

exports.MyObject = MyObject;
var MyObject = require('./MyObject').MyObject;

var myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined
::
export default class MyObject {
  constructor (foo) {
    this._foo = foo;
  }

  publicFun () {
    return this::privateFun('>>');
  }
}

function privateFun (prefix) {
  return prefix + this._foo;
}
import MyObject from './MyObject';

let myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // TypeError: myObject.privateFun is not a function

This is the best answer. The benefits of private methods, no junk.

.call

@janje Huh? That's the point of the question, there is no private f() in javascript (not at the moment).

@YvesM. The point of the question is choosing the best pattern that simulates it.

@changed what is the best compromise to have hidden functions (un-callable from outside), nice sintax (no .call) and small memory (no functions on the instance) ? Does that even exist ?

oop - JavaScript private methods - Stack Overflow

javascript oop private-methods
Rectangle 27 111

Simpler with Node.js

JavaScript uses prototypes and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.

Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; when a function is called as a method of an object, the function's local this keyword is bound to that object for that invocation.

var MyObject = (function () {

    // Constructor
    function MyObject (foo) {
        this._foo = foo;
    }

    function privateFun (prefix) {
        return prefix + this._foo;
    }

    MyObject.prototype.publicFun = function () {
        return privateFun.call(this, '>>');
    }

    return MyObject;
})();


var myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined

The call function allows us to call the private function with the appropriate context (this).

If you are using node.js, you don't need the IIFE because you can take advantage of the module loading system:

function MyObject (foo) {
    this._foo = foo;
}

function privateFun (prefix) {
    return prefix + this._foo;
}

MyObject.prototype.publicFun = function () {
    return privateFun.call(this, '>>');
}

exports.MyObject = MyObject;
var MyObject = require('./MyObject').MyObject;

var myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined
::
export default class MyObject {
  constructor (foo) {
    this._foo = foo;
  }

  publicFun () {
    return this::privateFun('>>');
  }
}

function privateFun (prefix) {
  return prefix + this._foo;
}
import MyObject from './MyObject';

let myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // TypeError: myObject.privateFun is not a function

This is the best answer. The benefits of private methods, no junk.

.call

@janje ? What's the problem with .call ? btw you can move from ES5 and use the :: bind operator (think about using babel)

@janje Huh? That's the point of the question, there is no private f() in javascript (not at the moment).

@YvesM. The point of the question is choosing the best pattern that simulates it.

oop - JavaScript private methods - Stack Overflow

javascript oop private-methods
Rectangle 27 2

Since Javascript is a prototypical language, it doesn't have the same sort of class inheritance that a language like, say, Java has. If you want a very simple instance of inheritance, you could try something like:

function baseservice() {
  this.loadAnimate = function () {
    $('#ajax-spinner').show();
  };
  this.loadComplete = function () {
    $('#ajax-spinner').hide();
  };
  this.apiEndpoint = function() {
    return "http://api.com/api/";
  };
};

var documentservice = new baseservice();
documentservice.sendRequest() = function() { /* ... */ }

Then, documentservice has all of baseservice's members (note the this. in baseservice's function declaration instead of var).

If you don't want to have to use the new keyword, you can create a function extend either adds a field pointing to baseservice (document.baseservice = baseservice) or does a deep (recursive) copy, then adds documentservice.sendRequest.

Of course, folks have already worked on this with things like ded/klass.

JS works very differently to classical inheritance languages. Strongly advice that the OP read Crockford's "JavaScript the Good Parts" book. amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/

jquery - Simple Example of Javascript Inheritance? - Stack Overflow

javascript jquery
Rectangle 27 99

JavaScript does not have block scope. Variables introduced with a bloc...

Bit late to the party, but I was exploring this issue today and noticed that many of the answers don't completely address how Javascript treats scopes, which is essentially what this boils down to.

So as many others mentioned, the problem is that the inner function is referencing the same i variable. So why don't we just create a new local variable each iteration, and have the inner function reference that instead?

Just like before, where each inner function outputted the last value assigned to i, now each inner function just outputs the last value assigned to ilocal. But shouldn't each iteration have it's own ilocal?

Turns out, that's the issue. Each iteration is sharing the same scope, so every iteration after the first is just overwriting ilocal. From MDN:

Important: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.

We can see this by checking ilocal before we declare it in each iteration:

This is exactly why this bug is so tricky. Even though you are redeclaring a variable, Javascript won't throw an error, and JSLint won't even throw a warning. This is also why the best way to solve this is to take advantage of closures, which is essentially the idea that in Javascript, inner functions have access to outer variables because inner scopes "enclose" outer scopes.

This also means that inner functions "hold onto" outer variables and keep them alive, even if the outer function returns. To utilize this, we create and call a wrapper function purely to make a new scope, declare ilocal in the new scope, and return an inner function that uses ilocal (more explanation below):

Creating the inner function inside a wrapper function gives the inner function a private environment that only it can access, a "closure". Thus, every time we call the wrapper function we create a new inner function with it's own separate environment, ensuring that the ilocal variables don't collide and overwrite each other. A few minor optimizations gives the final answer that many other SO users gave:

//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '<p>' + msg + '</p>';};

var funcs = {};
for (var i = 0; i < 3; i++) {
    funcs[i] = wrapper(i);
}
for (var j = 0; j < 3; j++) {
    funcs[j]();
}
//creates a separate environment for the inner function
function wrapper(ilocal) {
    return function() { //return the inner function
        console.log("My value: " + ilocal);
    };
}

I like how you explained the IIFE way as well. I was looking for that. Thank you.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 22

Creating a Pseudo-Classical Inheritance Pattern in JavaScript

If you want something similar to classes in JavaScript then there are a lot of libraries out there which provide it to you. For example using augment you could restructure your code as follows:

var augment = require("augment");

var ABC = augment(Object, function () {
    this.constructor = function (key, value) {
        this.key = key;
        this.value = value;
    };

    this.what = function () {
        alert("what");
    };
});

var XYZ = augment(ABC, function (base) {
    this.constructor = function (key, value) {
        base.constructor.call(this, key, value);
    };

    this.that = function () {
        alert("that");
    };
});

I don't know about you but to me this looks a lot like classical inheritance in C++ or Java. If this solves your problem, great! If is doesn't then continue reading.

In a lot of ways prototypes are similar to classes. In fact prototypes and classes are so similar that we can use prototypes to model classes. First let's take a look at how prototypal inheritance really works:

The above picture was taken from the following answer. I suggest you read it carefully. The diagram shows us:

  • Every constructor has a property called prototype which points to the prototype object of the constructor function.
  • Every prototype has a property called constructor which points to the constructor function of the prototype object.
  • We create an instance from a constructor function. However the instance actually inherits from the prototype, not the constructor.

This is very useful information. Traditionally we've always created a constructor function first and then we've set its prototype properties. However this information shows us that we may create a prototype object first and then define the constructor property on it instead.

function ABC(key, value) {
    this.key = key;
    this.value = value;
}

ABC.prototype.what = function() {
    alert("what");
};

However using our newfound knowledge we may write the same thing as:

var ABC = CLASS({
    constructor: function (key, value) {
        this.key = key;
        this.value = value;
    },
    what: function () {
        alert("what");
    }
});

function CLASS(prototype) {
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
}

As you can see encapsulation is easy to achieve in JavaScript. All you need to do is think sideways. Inheritance however is a different issue. You need to do a little more work to achieve inheritance.

augment
function augment(body) {
    var base = typeof this === "function" ? this.prototype : this;
    var prototype = Object.create(base);
    body.apply(prototype, arrayFrom(arguments, 1).concat(base));
    if (!ownPropertyOf(prototype, "constructor")) return prototype;
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
}

Notice that the last three lines are the same as that of CLASS from the previous section:

function CLASS(prototype) {
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
}

This tells us that once we have a prototype object all we need to do is get its constructor property and return it.

The first three lines of augment are used to:

  • Get the base class prototype.
  • Create a derived class prototype using Object.create.
  • Populate the derived class prototype with the specified properties.

That's all that there is to inheritance in JavaScript. If you want to create your own classical inheritance pattern then you should be thinking along the same lines.

Every JavaScript programmer worth their salt will tell you that prototypal inheritance is better than classical inheritance. Nevertheless newbies who come from a language with classical inheritance always try to implement classical inheritance on top of prototypal inheritance, and they usually fail.

They fail not because it's not possible to implement classical inheritance on top of prototypal inheritance but because to implement classical inheritance on top of prototypal inheritance you first need to understand how true prototypal inheritance works.

However once you understand true prototypal inheritance you'll never want to go back to classical inheritance. I too tried to implement classical inheritance on top of prototypal inheritance as a newbie. Now that I understand how true prototypal inheritance works however I write code like this:

function extend(self, body) {
    var base = typeof self === "function" ? self.prototype : self;
    var prototype = Object.create(base, {new: {value: create}});
    return body.call(prototype, base), prototype;

    function create() {
        var self = Object.create(prototype);
        return prototype.hasOwnProperty("constructor") &&
            prototype.constructor.apply(self, arguments), self;
    }
}

The above extend function is very similar to augment. However instead of returning the constructor function it returns the prototype object. This is actually a very neat trick which allows static properties to be inherited. You can create a class using extend as follows:

var Abc = extend(Object, function () {
    this.constructor = function (key, value) {
        this.value = 333 + Number(value);
        this.key = key;
    };

    this.what = function () {
        alert("what");
    };
});

Inheritance is just as simple:

Remember however that extend does not return the constructor function. It returns the prototype object. This means that you can't use the new keyword to create an instance of the class. Instead you need to use new as a method, as follows:

var x = Xyz.new("x", "123");
var y = Xyz.new("y", "456");
var it = Abc.new("it", "789");

This is actually a good thing. The new keyword is considered harmful and I strongly recommend you to stop using it. For example it's not possible to use apply with the new keyword. However it is possible to use apply with the new method as follows:

var it = Abc.new.apply(null, ["it", "789"]);

Since Abc and Xyz are not constructor functions we can't use instanceof to test whether an object is an instance of Abc or Xyz. However that's not a problem because JavaScript has a method called isPrototypeOf which tests whether an object is a prototype of another object:

alert(x.key + ": " + x.value + "; isAbc: " + Abc.isPrototypeOf(x));
alert(y.key + ": " + y.value + "; isAbc: " + Abc.isPrototypeOf(y));

alert(it.key + ": " + it.value + "; isAbc: " + Abc.isPrototypeOf(it));
alert(it.key + ": " + it.value + "; isXyz: " + Xyz.isPrototypeOf(it));
isPrototypeOf
instanceof
alert(Abc.isPrototypeOf(Xyz)); // true

Besides this minor change everything else works just like it did before:

x.what();
y.that();

it.what();
it.that(); // will throw; it is not Xyz and does not have that method

What else does true prototypal inheritance offer? One of the biggest advantages of true prototypal inheritance is that there's no distinction between normal properties and static properties allowing you to write code like this:

var Xyz = extend(Abc, function (base) {
    this.empty = this.new();

    this.constructor = function (key, value) {
        base.constructor.call(this, key, value);
    };

    this.that = function () {
        alert("that");
    };
});

Notice that we can create instances of the class from within the class itself by calling this.new. If this.constructor is not yet defined then it returns a new uninitialized instance. Otherwise it returns a new initialized instance.

In addition because Xyz is the prototype object we can access Xyz.empty directly (i.e. empty is a static property of Xyz). This also means that static properties are automatically inherited and are no different from normal properties.

Finally, because the class is accessible from within the class definition as this, you can created nested classes which inherit from the class which they are nested within by using extend as follows:

var ClassA = extend(Object, function () {
    var ClassB = extend(this, function () {
        // class definition
    });

    // rest of the class definition

    alert(this.isPrototypeOf(ClassB)); // true
});

There's a known issue that the properties like instance.What in fact are not inherited from the prototype and each instance has its own property, which can be solved by adding an argument and passing the prototype to the initialize function such as function (instance, prototype, _super); but that approach doesn't work with a closure captures the arguments of the constructor. I'm still reading your answer, and sorry for giving you migraines ..

augment seems a good solution but I'm wondering how to declare an instance of type which is being declared, such as declaring Xyz.Empty=new Xyz(); inside while Xyz is not yet declared, using this.constructor to do that may reduce the readability ..

Another problem with augment that I cannot see a solution is to declare nesting classes which derive from the declaring class.

extend

@AaditMShah: Thanks for the update, but I cannot upvote twice :-). However, I don't really like your static properties, which are just prototype properties (and accessing them on the instances might trap some people into trying to assign them on the instances). I had more thought of something like in this answer of mine where there are two separate (cross-linked) prototype chains for the Class objects and the instances.

javascript - How to achieve pseudo-classical inheritance right on the ...

javascript inheritance types prototype
Rectangle 27 9

Cross-browser with jQuery

it is generally recommended to avoid inline JavaScript, but rarely is there an example of how to do it. Here is my way of attaching events to buttons. I'm not entirely happy with how much longer the recommended method is compared to a simple onClick attribute.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function($){
    $(document).on('click', '.click-me', function(e){
      doSomething.call(this, e);
    });
})(jQuery);

function insertHTML(str){
  var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
  lastScript.insertAdjacentHTML("beforebegin", str);
}

function doSomething(event){
  console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>

<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>

<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">

<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>

</body>
</html>

You can run this before the document is ready, clicking the buttons will work because we attach the event to the document.

Here is a jsfiddle For some strange reason the insertHTML function does not work in it even though it works in all my browsers.

insertHTML
document.write
<script>
document.write('<button class="click-me" id="btn1">Button 1</button>');
</script>

I'm always wondering how events can be as efficient (performance-wise) as inline onclicks. I guess they must be harder to keep track of?

depends on your class naming convention, if the convention is meaningful then it will be as easy to find as onclicks

html - JavaScript - onClick to get the ID of the clicked button - Stac...

javascript html
Rectangle 27 9

Cross-browser with jQuery

it is generally recommended to avoid inline JavaScript, but rarely is there an example of how to do it. Here is my way of attaching events to buttons. I'm not entirely happy with how much longer the recommended method is compared to a simple onClick attribute.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function($){
    $(document).on('click', '.click-me', function(e){
      doSomething.call(this, e);
    });
})(jQuery);

function insertHTML(str){
  var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
  lastScript.insertAdjacentHTML("beforebegin", str);
}

function doSomething(event){
  console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>

<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>

<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">

<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>

</body>
</html>

You can run this before the document is ready, clicking the buttons will work because we attach the event to the document.

Here is a jsfiddle For some strange reason the insertHTML function does not work in it even though it works in all my browsers.

insertHTML
document.write
<script>
document.write('<button class="click-me" id="btn1">Button 1</button>');
</script>

I'm always wondering how events can be as efficient (performance-wise) as inline onclicks. I guess they must be harder to keep track of?

depends on your class naming convention, if the convention is meaningful then it will be as easy to find as onclicks

html - JavaScript - onClick to get the ID of the clicked button - Stac...

javascript html
Rectangle 27 1

var REPLACEMENTS = {
    'example-phrase': 'Example Phrase',
    'example2-phrase': 'Example 2 Phrase',
    'example-solution': 'Example & Solution'
}

function doReplacement(input) {
    for (var key in REPLACEMENTS) {
        input = input.replace(key, REPLACEMENTS[key]);
    }

    return input;
}

Might not be the most performant solution though. You might need to ask yourself: Do you need case insensitivity? Can a single input contain more than one of the strings that need to be replaced? Is the string itself exactly equal to the replacement key or does it contain it?

h2
$(function() {
    var REPLACEMENTS = {
        'example-phrase': 'Example Phrase',
        'example2-phrase': 'Example 2 Phrase',
        'example-solution': 'Example & Solution'
    }

    function doReplacement(input) {
        for (var key in REPLACEMENTS) {
            input = input.replace(key, REPLACEMENTS[key]);
        }

        return input;
    }

    $('h2').each(function() {
        var $this = $(this);
        $this.html(doReplacement($this.html()));
    });
});

Exactly how you have it is how I would need it. The string getting replaced are always the same and what needs to replace them is always the same. What about this code is a performance hindrance?

It depends on how often you will run this and how many replacements there will be. If you this with, say, 20 headlines and 50 possible replacements you don't really need to care about its performance. It might become an issue if you run this over thousands of texts with hundreds of replacements.

Ah, luckily just running on 1 page and probably only 10-20 replacements will happen. Do I need some other code to have this run automatically as soon as the page loads?

Perfect! Thank you. Answered accepted, exactly what I needed. I did have to change $ to jQuery for no conflict (I couldn't determine what other script was causing it) and changed h2 to .replacement so I could apply this function with a css class. jsfiddle.net/codeview/GSZLR

Simple/Basic Jquery or Javascript String Replace for Multiple Values -...

javascript jquery str-replace
Rectangle 27 88

If you look at the source code you can see that I am calling the Twitter API using .getJSON.

So your example would be: THIS IS TESTED AND WORKS (You can go to http://smallcoders.com/javascriptdevenvironment.html to see it in action)

//JAVASCRIPT

$.getJSON('http://www.write-about-property.com/jsonp.php?callback=?','firstname=Jeff',function(res){
    alert('Your name is '+res.fullname);
});

//SERVER SIDE
  <?php
 $fname = $_GET['firstname'];
      if($fname=='Jeff')
      {
          //header("Content-Type: application/json");
         echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';

      }
?>

Note the ?callback=? and +res.fullname

And what about the server-sided part of the story? :)

never echo a user provided parameter without sanitizing!

Simple jQuery, PHP and JSONP example? - Stack Overflow

php jquery ajax json jsonp
Rectangle 27 2

var ex1 = "example-phrase";
var res1 = ex1.replace("-", " ");
res1 = res1.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});

The above solution works for the first case. For the 3rd case, just add the following,

var ex3 = "example-solution";
var res3 = ex3.replace("-", " ");
res3 = res3.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});
res3 = res3.replace(" ", " & ");

I feel that checking every time you get a response isn't feasible.

Simple/Basic Jquery or Javascript String Replace for Multiple Values -...

javascript jquery str-replace
Rectangle 27 1564

Well, the problem is that the variable i, within each of your anonymous functions, is bound to the same variable outside of the function.

What you want to do is bind the variable within each function to a separate, unchanging value outside of the function:

var funcs = [];

function createfunc(i) {
    return function() { console.log("My value: " + i); };
}

for (var i = 0; i < 3; i++) {
    funcs[i] = createfunc(i);
}

for (var j = 0; j < 3; j++) {
    funcs[j]();                        // and now let's run each one to see
}
var funcs = [];

function createfunc(i) {
    return function() { console.log("My value: " + i); };
}

for (var i = 0; i < 3; i++) {
    funcs[i] = createfunc(i);
}

for (var j = 0; j < 3; j++) {
    funcs[j]();                        // and now let's run each one to see
}

Since there is no block scope in JavaScript - only function scope - by wrapping the function creation in a new function, you ensure that the value of "i" remains as you intended.

Update: with the relatively widespread availability of the Array.prototype.forEach function (in 2015), it's worth noting that in those situations involving iteration primarily over an array of values, .forEach() provides a clean, natural way to get a distinct closure for every iteration. That is, assuming you've got some sort of array containing values (DOM references, objects, whatever), and the problem arises of setting up callbacks specific to each element, you can do this:

var someArray = [ /* whatever */ ];
// ...
someArray.forEach(function(arrayElement) {
  // ... code code code for this one element
  someAsynchronousFunction(arrayElement, function() {
    arrayElement.doSomething();
  });
});

The idea is that each invocation of the callback function used with the .forEach loop will be its own closure. The parameter passed in to that handler is the array element specific to that particular step of the iteration. If it's used in an asynchronous callback, it won't collide with any of the other callbacks established at other steps of the iteration.

If you happen to be working in jQuery, the $.each() function gives you a similar capability.

Update 2: ECMAScript 6 (ES6), the newest version of JavaScript, is now starting to be implemented in many evergreen browsers and backend systems. There are also transpilers like Babel that will convert ES6 to ES5 to allow usage of new features on older systems.

ES6 introduces new let and const keywords that are scoped differently than var-based variables. For example, in a loop with a let-based index, each iteration through the loop will have a new value of i where each value is scoped inside the loop, so your code would work as you expect. There are many resources, but I'd recommend 2ality's block-scoping post as a great source of information.

for (let i = 0; i < 3; i++) {
    funcs[i] = function() {
        console.log("My value: " + i);
    };
}

Beware, though, that IE9-IE11 and Edge prior to Edge 14 support let but get the above wrong (they don't create a new i each time, so all the functions above would log 3 like they would if we used var). Edge 14 finally gets it right.

In new version of javascript, one could use let which is block scoped.

function createfunc(i) {     return function() { console.log("My value: " + i); }; }
Function.bind()

@Wladimir: Your suggestion that .bind() is "the correct answer" isn't right. They each have their own place. With .bind() you can't bind arguments without binding the this value. Also you get a copy of the i argument without the ability to mutate it between calls, which sometimes is needed. So they're quite different constructs, not to mention that .bind() implementations have been historically slow. Sure in the simple example either would work, but closures are an important concept to understand, and that's what the question was about.

Please stop using these for-return function hacks, use [].forEach or [].map instead because they avoid reusing the same scope variables.

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures
Rectangle 27 1562

Well, the problem is that the variable i, within each of your anonymous functions, is bound to the same variable outside of the function.

What you want to do is bind the variable within each function to a separate, unchanging value outside of the function:

var funcs = [];

function createfunc(i) {
    return function() { console.log("My value: " + i); };
}

for (var i = 0; i < 3; i++) {
    funcs[i] = createfunc(i);
}

for (var j = 0; j < 3; j++) {
    funcs[j]();                        // and now let's run each one to see
}

Since there is no block scope in JavaScript - only function scope - by wrapping the function creation in a new function, you ensure that the value of "i" remains as you intended.

Update: with the relatively widespread availability of the Array.prototype.forEach function (in 2015), it's worth noting that in those situations involving iteration primarily over an array of values, .forEach() provides a clean, natural way to get a distinct closure for every iteration. That is, assuming you've got some sort of array containing values (DOM references, objects, whatever), and the problem arises of setting up callbacks specific to each element, you can do this:

var someArray = [ /* whatever */ ];
// ...
someArray.forEach(function(arrayElement) {
  // ... code code code for this one element
  someAsynchronousFunction(arrayElement, function() {
    arrayElement.doSomething();
  });
});

The idea is that each invocation of the callback function used with the .forEach loop will be its own closure. The parameter passed in to that handler is the array element specific to that particular step of the iteration. If it's used in an asynchronous callback, it won't collide with any of the other callbacks established at other steps of the iteration.

If you happen to be working in jQuery, the $.each() function gives you a similar capability.

Update 2: ECMAScript 6 (ES6), the newest version of JavaScript, is now starting to be implemented in many evergreen browsers and backend systems. There are also transpilers like Babel that will convert ES6 to ES5 to allow usage of new features on older systems.

ES6 introduces new let and const keywords that are scoped differently than var-based variables. For example, in a loop with a let-based index, each iteration through the loop will have a new value of i where each value is scoped inside the loop, so your code would work as you expect. There are many resources, but I'd recommend 2ality's block-scoping post as a great source of information.

for (let i = 0; i < 3; i++) {
    funcs[i] = function() {
        console.log("My value: " + i);
    };
}

Beware, though, that IE9-IE11 and Edge prior to Edge 14 support let but get the above wrong (they don't create a new i each time, so all the functions above would log 3 like they would if we used var). Edge 14 finally gets it right.

function createfunc(i) {     return function() { console.log("My value: " + i); }; }
Function.bind()

@Wladimir: Your suggestion that .bind() is "the correct answer" isn't right. They each have their own place. With .bind() you can't bind arguments without binding the this value. Also you get a copy of the i argument without the ability to mutate it between calls, which sometimes is needed. So they're quite different constructs, not to mention that .bind() implementations have been historically slow. Sure in the simple example either would work, but closures are an important concept to understand, and that's what the question was about.

Please stop using these for-return function hacks, use [].forEach or [].map instead because they avoid reusing the same scope variables.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

JavaScript closure inside loops – simple practical example - Stack Ove...

javascript loops closures