Maybe this question have beend posted before what I just do not know how to search for it.
I'd like to know how can I create a method like .replace(), or .toString(). I mean, if I have a variable and I want to search if that variable have number or not, like to do this
var someVariable = "hello 34, how are you";
var containsIntsNumber = someVariable.SearchInteger();//being search integer my custom method
if(containsIntsNumber )
{
console.log("It does have integers");
}
How can I achieve this?
You can modify the prototype on the String object.
String.prototype.someFunction = function () {
/* Your function body here; you can use
this to access the string itself */
};
You can add it to the string prototype.
String.prototype.SearchInteger = function(){
//do stuff
}
the you can call it like this
var someVariable = "hello 34, how are you";
var containsIntsNumber = someVariable.SearchInteger();
Adding additional functions to prototypes can be a bit controversial in the JS community. Be warned that it will then show up when you enumerate over the properties of the variable, and it could theoretically be overwritten or used for a different purpose by an external library.
This can be achieved in few ways. Have a function that return boolean value or extend string prototype so that you can call this method directly on string variable.
This will check wheather string has a number.
String.prototype.hasInteger = function(){
return /\d/.test(this);
}
However it is not recommended to augment native objects, so my suggestion would be just use a function.
function hasInteger(value){
return /\d/.test(value);
}
if(!String.prototype.SearchInteger)
{
Object.defineProperty(String.prototype, 'SearchInteger',
{
value: function()
{
// body of your function here
},
enumerable: false
});
}
You will have to extend the prototype of String in this case. As String is an inbuilt type, It is not recommended to extend their prototype, but you can still do if you fancy(but dont!)
easy example would be something like
String.prototype.SearchInteger = function () {
return this.test(/^.*\d+.*$/g);
};
this should work, though I didn't test.
Related
I'm building a Backbone Marionette Application. In Marionette you can do something like:
Marionette.Application.extend({
regions: {
mainRegion: function(){return someCondition?"#A":"#B"},
otherRegion: "#something"
}
})
I'm trying to implement this in my application with custom objects. What is the best way to achieve this?
Currently, I'm checking for every value:
if(typeof obj == "function") {
this.data.obj = obj();
}
else {
this.data.obj = obj;
}
or the corresponding ?: expression.
Is there an easier way to do this?
Underscore has a result method that does exactly what you want (see http://underscorejs.org/#result)
You can find the implementation here: http://underscorejs.org/docs/underscore.html#section-128
There is a potential solution (cue screaming) in adding value() [not to be confused with valueOf()] to every prototype you're interested in.
Function.prototype.value = function () { return this(); }; // Probably should be .call() so you can do arguments if necessary.
String.prototype.value = function () { return this; };
etc.
Then you can use this.data.obj = obj.value() for all calls.
If you're queasy about adding functions to prototypes, this isn't a solution you'd want to use. Otherwise you could write a wrapper function that takes obj as an argument and returns the right thing based on the type.
The duck typing idea proposed by dandavis is also good IMHO.
let say I've got this kind of code:
var obj1 = {test: false};
function testCondition(condition){
if (!condition){
testCondition(condition);
}
}
testCondition(obj1.test);
above code will pass false as argument to testCondition. How can I do to pass reference to obj1.test instead of passing it's value?
EDIT
wow, thanks for quick responses!! :) But I would like to add, that I cannot pass the whole object, because I would like to build one generic function/method which would just check parameter and do onComplete callback or onError callback. Above code is only example of situation where I am right now.
You have two choices, from what I can see:
Pass the object itself, instead of its member. You can then access and modify the member:
function testCondition(object) {
if (!object.test) {
testCondition(object);
}
}
testCondition(obj1)
Alternatively, since you're changing a single value, you can have that value be returned by the function:
function testCondition(condition) {
if (!condition){
return testCondition(condition);
}
}
obj1.test = testCondition(obj1.test);
FYI, your code as you've displayed it right now will cause an infinite recursion if condition is false.
What's wrong with return values?
Alternatively you can wrap the argument in an object:
function foo(arg) {
var val = arg.val;
// do something with val
arg.val = val;
}
var arg = {val:"bar"};
foo(arg);
// do something with arg.val
You can't.
Pass obj1 instead, then examine condition.test inside the function.
You can't. JavaScript passes objects and arrays by reference, primitives (integers, strings, booleans) by value. What you're asking for is impossible, except by bad work-arounds:
function ugly(result) {
result.success = true;
}
var result = {};
ugly(result);
Instead, just return your value. It's how JavaScript is meant to work.
pass the whole object instead of its property:
testCondition(obj1);
and then
if(!passedObj.test){
etc...
using prototype method we can create new methods... like...
Object.prototype.newMethod=function(){
// do something
}
Here I am defining the newMethod with an anonymous function... now if I want to use this method, I have to use it like: <object>.newMethod();
But now I want to create a new method which I can use like: <object>.newMethod;... no brackets... How can I do that...??
please don't use any jQuery...
Erm, you can't. To call a method, you write parentheses after it. Otherwise you're just referencing it.
The only exception to this rule is when you write something like new Date, where the parentheses are implict due to the new keyword and only because there are no arguments given.
I can't really understand why you would want to do that, but it is possible, albeit with a nasty hacky workaround. What you're actually looking for, AFAIK, is a magic property (like the someArray.length property).
var foo = {val:'foo'};
foo.length = (function(that)
{
return function()
{
return that.val.length;
}
})(foo);
//at this point foo.length(); returns 3, but still requires parentheses
//so, build another closure, and assign a valueOf method to the lenth method:
foo.length.valueOf = (function(method)
{
return function()
{
return method();//call the length method
}
})(foo.length);
console.log(foo.length +1);//logs 4
foo.val += 'bar';
console.log(foo.length);//logs 6
//BUT:: be carefull!!
alert(foo.length);//coerces to string, we haven't redefined the toString method, so the function code will be alerted
alert(foo.length + '');//alerts 6
This is just to show you that, yes it is theoretically possible, but please, please, don't use this kind of overly polluted hacks... I haven't thoroughly tested this, but ATM, I've already noticed that console.log(foo.length); can return a different value, not sure why, yet:
foo = {val:'foo'};
foo.length = (function(that){return function(){ return that.val.length;};})(foo);
foo.length.valueOf = (function(method){return function(){return method();};})(foo.length);
foo.length;//returns 3, great
foo.val += 'bar';
console.log(foo.length);//logged 3 at first, now it's back to logging 6!<-- don't trust this is the conclusion
The only way to call a function without parenthesis would be to define it using getters and setters.
Note these are new to JavaScript 1.8 and are not supported by all browsers.
Is there any way to comparing function pointers in javascript? Basically, I want to see if I've added the same function multiple times to an array, and then only add it once. Yeah, I can program my way around it, but it would be much easier to do it this way.
The code below does NOT use an array, but illustrates the point I'm trying to make. I'd like for oldPointer to only be set if a myPointer is a different function.
Here is some example code:
function test()
{
}
test.prototype.Loaded = function()
{
this.loaded = true;
}
test.prototype.Add = function(myPointer)
{
if (this.oldPointer != myPointer) //never the same
{
this.oldPointer = myPointer;
}
}
test.prototype.run = function()
{
this.Add(this.Loaded.bind(this));
this.Add(this.Loaded.bind(this)); //this.oldPointer shouldn't be reassigned, but it is
}
var mytest = new test();
test.run();
Assuming bind is a function that uses Function.apply() to create a function closure binding this to the context, this.Loaded.bind(this) will produce a new function every time it is called. That is why your code does not work. Unfortunately there is no way to reference this.Loaded from the function object produced by bind(), so comparison is impossible.
If instead you did something like the below, your check would work, though I'm not sure how much use it would be to you.
test.prototype.run = function()
{
var loadedFn = this.Loaded.bind(this);
this.Add(loadedFn);
this.Add(loadedFn);
}
Please clarify exactly what you are trying to do if you want a better answer.
If your question is "How do I efficiently avoid adding the same function to a given array twice?" the simplest way to program around it is obviously:
// Add f to a if and only if it is not already in a
if (a.indexOf(f) < 0) {
a.push(f);
}
If the linear complexity of indexOf bothers you, and you are only concerned about a single array, you can get very fancy and store the fact that the function was loaded in the function itself:
// Add f to a if and only if it is not already in a
if (! f.alreadyAddedToA) {
a.push(f);
f.alreadyAddedToA = true;
}
Pick any name for the hack property.
If there are multple arrays you are worried about, you can store a kind of hashmap (hacked objects in JS, with suitable keys) inside the function.
This sort of thing works in JavaScript
function main() {
return 1;
}
main.sub = function () {
return 2;
};
main(); // 1
main.sub(); // 2
and seems useful for doing stuff like
function props() {
return { color: props.color(), size: props.size() };
}
props.color = function () {
// calculate and return color
};
props.size = function () {
// calculate and return size
};
so that you'd have an easy way to pull in an object of all the props using prop() but if you only need one you can call for it directly. Is that type of setup okay?
Even though it is absolutely legal, I'd say it is the wrong utilization of sub methods. It confuses the function with the return value of said function.
I would say a proper use of submethods within functions is when you want to add metadata for the function. Let's say you want to set a property for the function like documentation or whether you want it to be obfuscated. Then you can set the property for the function instead of the underlying object.
Even though your usage may save some writing, it makes reading the code much harder IMHO. You should always strive for ease of readability, not of writing.
Generally this is probably not good practice:
calling: props.color(); will do the same thing as calling props().color.
What would be a better pattern would be something as follows:
var props = function() {
var theColor = function() {
// calculate the color
};
var theSize = function() {
// calculate the size
};
return {
color: theColor(),
size: theSize()
}
}
var someprops = new props();
You could instead of having for example theColor() as the object for color, you could leave it as the function: So the return would be
return {
color: theColor,
size: theSize
}
The difference being that the props.color == "function" whereas in the previous example props.color would've equaled the result of the function.
That looks useful, but it isn't very obvious what's happening when you use it.
The expression props.color() returns the same as the similar expression props().color, but the performance differs as the latter also calculates the other properties, which are then discarded. It's easy to misuse the feature without noticing, so you should consider using an approach where the usage shows more clearly what's actually happening in the code.