Friday, October 22, 2010

Javascript / JQuery / ExtJS / OOJS

Javascript OOP Inheritance
<script>
function Parenizor(value) {
this.setValue = function (value) { this.value = value; return this; };
this.getValue = function () { return this.value; };
this.toString = function () { return '(' + this.getValue() + ')'; };
this.setValue(value);
}

function child() {
this.toString = function () { return ' - ' + this.getValue() + ' - '; };
}

child.prototype = new Parenizor("RamTest");
ch = new child();
console.log(ch.toString());
ch.setValue("RamTest Modified");
console.log(ch.getValue());
</script>

How to check Cookies are enabled or not in JS

<script> if(navigator.cookieEnabled) { alert('enabled') } </script>

Javascript Closures

To create a closure, you nest a function inside of a function. That inner function has access to all variables in its parent function’s scope. This comes in handy when creating methods and properties in object oriented scripts. Here is a simple example that demonstrates the use of a closure:

function myObject() {
this.property1 = "value1";
this.property2 = "value2";
var newValue = this.property1;
this.performMethod = function() {
myMethodValue = newValue;
return myMethodValue;
};
}
var myObjectInstance = new myObject();
alert(myObjectInstance.performMethod());


Eg:2
function sayHello2(name) {
var text = 'Hello ' + name; // local variable
var sayAlert = function() { alert(text); }
return sayAlert;
}

* A function within another function is called closures
* A closure is the local variables for a function

Validates regular hostname, ip address
var IpAddress = new RegExp( /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/);

var HostName = new RegExp(/^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$/);

//#-- multiple in single regexp
var HostNameAndIp = new RegExp(/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$/);


Datatypes in Javascript
Datatype EXAMPLE

Numbers Any number, such as 17, 21, or 54e7
Strings "Greetings!" or "Fun"
Boolean Either true or false
Null A special keyword for exactly that – the null value (that is, nothing)

No comments:

Post a Comment