I have three questions and all of them are related.
1) I want to add a property called bar
to String
object.
I did this
String.prototype.bar=function() {console.log("jjjj");}
"mystring.bar//function()
"mystring".bar()//jjjj
but I want to use "mystring".bar
(no function call) just like how we use "mystring".length
to get the length of string. how can I acheive this?
2) now I want to change the inbuilt method of length on String object. so I did this
>>> String.prototype.length=function(){console.log("xxx");};
function()
>>> "mmmm".length
4
but the length method has not changed. it still returns the length of string only. Note: I am changing this method only on console for learning purposes
3) I am having difficulty understanding this function from the book, javascript, the good parts by Crockford.
(pg no 40)
here is the method to augment String object. It replace HTML entities in a string and replace them with their equivalents
String.method('deentityify',function() {
var entity = {
quot:'";,
lt:'<',
gt:'<'
};
//return the deentityify method
return function() {
return this.replace(/&([^&;]+);/g,
function (a,b) {
var r = entity[b];
return typeof r==='string' ? r : a;
}
);
};
}());
'<">'.dentityify();//<">
questions on this problem: 1)since no prototpye is used, does this method is available on all String objects to be used.
2)in the return this.replace(..
part of the above, I do not understand what parameters are given to a and b.
ie when I call '<">'.dentityify();
, what does a and b
get and how that anonymous function is executed.
Thank you all for the help