Mấy anh chi hướng dẫn hết rồi nhé
tặng chú cái note về javascript:
http://www.w3schools.com/js/js_function_parameters.asp
INTRODUCTION
Javascript, a scripting language, is only compiled when an interpreter (built into the web browser) reads it.
So when your web browser reads a web page with a Javascript program in it, the web browser translates the Javascript into something the computer understands.
Case-sensitive
Everything is a variable and the later variable will override the sooner one if they are the same name.
function run(speed, time) {
alert('You are running at ' + speed + ' km/h and you have been running for ' + time + ' minutes');
}
....
var run = function() {
alert('You are running.');
}
...
run = 5;
...
run(); // try to call a function and got an error: a is not a function
alert(run);
Recommendations:
- Declare local variables if possible (var variable).
- Using Object-oriented in Javascript
- Do not put <script>...</script> many places in a web page, just "one entry point" for easier maintaining in the future.
DATA TYPE
In JavaScript there are 5 different data types that can contain values:
string
number
boolean
object
function
There are 3 types of objects:
Object
Date
Array
And 2 data types that cannot contain values:
null
undefined
1) The "typeof" Operator
You can use the "typeof" operator to find the data type of a JavaScript variable.
Example
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof NaN // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns object
typeof new Date() // Returns object
typeof function () {} // Returns function
typeof myCar // Returns undefined (if myCar is not declared)
typeof null // Returns object
As you can see above, you cannot use "typeof" to identify if an object is an JavaScript Array or a JavaScript Date (always returns object). You can use the "constructor" property below to do that.
2) The "constructor" Property
The "constructor" property to returns the constructor function for all JavaScript variables.
Example
"John".constructor // Returns function String() { [native code] }
(3.14).constructor // Returns function Number() { [native code] }
false.constructor // Returns function Boolean() { [native code] }
[1,2,3,4].constructor // Returns function Array() { [native code] }
{name:'John', age:34}.constructor // Returns function Object() { [native code] }
new Date().constructor // Returns function Date() { [native code] }
function () {}.constructor // Returns function Function(){ [native code] }
You can check the constructor property to find out if an object is an Array (contains the word "Array"):
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
You can check the constructor property to find out if an object is a Date (contains the word "Date"):
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
3) Type Conversion
a) Automatic type conversion
var numOfShoes = '2';
var numOfStocks = 2;
var totalItems = numOfShoes + numOfStocks;
alert(totalItems); // '22' or 4?
if (numOfShoes == numOfStocks) { // convert data type automatically before comparing
}
if (numOfShoes === numOfStocks) { // does not convert data type, so always returns "false" when two operands are not the same type
}
b) Using functions
- Every object/variable could be converted to a string by using "toString()" function.
- Using Number(), String(), Boolean(), Date()
String(false) // returns "false"
String(true) // returns "true"
false.toString() // returns "false"
true.toString() // returns "true"
(123).toString() // return "123"
String(123) // returns "123"
Number("3.14") // returns 3.14
Number(" ") // returns 0
Number("") // returns 0
Number("99 88") // returns NaN
Number(false) // returns 0
Number(true) // returns 1
d = new Date();
Number(d) // returns 1404568027739
OBJECT
Object is the main data type in JavaScript. "Everything" in JavaScript is an Object. Even primitive data types (except null and undefined) can be treated as objects.
Booleans can be objects (or primitive data treated as objects)
Numbers can be objects (or primitive data treated as objects)
Strings are also objects (or primitive data treated as objects)
Dates are always objects
Maths and Regular Expressions are always objects
Arrays are always objects
Even functions are always objects
A JavaScript object is a complex variable, with properties and methods.
1) Properties
2 ways to access the property of an object:
objectName.property
OR
objectName[property]
Example
person.lastName;
person["lastName"];
2) Methods
Call a method:
objectName.methodName()
3) The "this" Keyword:
- "this" is the object (instance) that "owns" the current code.
- The value of this, when used in a function, is the object that "owns" the function.
- The value of this will become the "new" object when the constructor is used to "create an object".
OBJECT'S CLASS
1) Static Class (could not create an instance) - also called Object literals: should only be used for simple objects setups, such as
pure JSON data
a) Using new Object()
var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
person.run = function() {
this.state = "running";
this.speed = 15; // km/h
}
b) Using literal notation {}
var timObject = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor: "blue",
address: {
country: "US",
state: "CA"
},
run : function() {
this.state = "running";
this.speed = 15; // km/h
}
};
2) Normal Class:
Using a Object Constructor (Javascript function) to define a class. Then using "new" operator with its constructor to create an instance object of the class:
function Cat(name) {
this.name = name;
this.talk = function() {
alert( this.name + " say meeow!" )
}
}
cat1 = new Cat("felix")
cat1.talk() //alerts "felix says meeow!"
cat2 = new Cat("ginger")
cat2.talk() //alerts "ginger says meeow!"
NOTE: in Javascript, a function always returns a value. If you don't return anything in it, it will return "this" object.
There are features that still remain valid in JavaScript pseudo
classes, such as "private members" and "privileged methods" that are not
available in the object literals.
The following is a typical class definition using a constructor function:
var MyClass = function () {
// private property and method
var myPrivateVariable, myPrivateFunction;
myPrivateVariable = "This is a private variable";
myPrivateFunction = function (x) {
return x + 1;
};
// public property and method
this.myPublicProperty = "This is a public property";
this.myPublicMethod = function () {
return myPrivateVariable;
}
}
JavaScript has built-in constructors for native objects:
var x1 = new Object(); // A new Object object
var x2 = new String(); // A new String object
var x3 = new Number(); // A new Number object
var x4 = new Boolean() // A new Boolean object
var x5 = new Array(); // A new Array object
var x6 = new RegExp(); // A new RegExp object
var x7 = new Function(); // A new Function object
var x8 = new Date(); // A new Date object
As you can see, JavaScript has object versions of the primitive data types String, Number, and Boolean.
There is no reason create complex objects. Primitive values execute much faster.
var x1 = {}; // new object
var x2 = ""; // new primitive string
var x3 = 0; // new primitive number
var x4 = false; // new primitive boolean
var x5 = []; // new array object
var x6 = /()/ // new regexp object
var x7 = function(){}; // new function object
a) Using "prototype" property to add more methods:
Cat.prototype.changeName = function(name) {
this.name = name;
}
firstCat = new Cat("pursur")
firstCat.changeName("Bill")
firstCat.talk() //alerts "Bill says meeow!"
b) JavaScript Objects are Mutable
Object are mutable: They are addressed by reference, not by value.
If y is an object, the following statement will not create a copy of y:
var x = y; // This will not create a copy of y.
The object x is not a copy of y. It is y. Both x and y points to the same object.
Any changes to y will also change x, because x and y are the same object.
c) Loop through properties of an object:
firstCat = new Cat("pursur")
firstCat.changeName("Bill")
for (var x in firstCat) {
alert(x + " - " + firstCat[x]);
}
d) Encapsulation:
function Cat(name) {
var aName = name;
var talk = function() {
alert(aName + " say meeow!");
}
.......
return {
name: aName,
talk: talk
}
}
=======================================================================
THE MODULE PATTERN
JavaScriptdoesn't have the concept of namespace, andfurthermore, managing
the global variable scoping is not easy. In a complex application using several
third-party libraries and frameworks, we really need something that can be used
as a sandbox to ensure the uniqueness for symbols and identifiers.
In this situation, we can use one of the most known JavaScript idiomatic patterns:
the module pattern. This pattern is a good solution if we need to introduce a class
definition sandboxing, not only to "protect" our names and signatures, but also
because it's very useful when we work in a team and every member has to focus
on different parts of the solution. In fact, with this kind of magic box, we can
individually test our classes and be sure that they will work when we put every
part together.
The module patternis based on self-executing functions, another well-known
idiomatic JavaScript syntax with several implementations, such as the following:
this.myModule = (function (module) {
module.MyClass = function () {
//MyClass definition
}
return module;
}(this.myModule || {}));
Here's a brief explanation:
- 'this.myModule' is a property assignment: 'this' is the global JavaScript object
(in a web browser it's the 'window' object), 'myModule' is the property that will
contain the module definition. It's important that this identifier is as unique
as possible because it will be exposed to every other library (it's our brand
identifier such as 'jQuery' or 'ko').
- '(function (module) {…}(…))' is a self-executing function. There is the
anonymous function definition first and immediately after there is its
invocation (the two outer parentheses are a common habit, placed to inform
that the enclosed function is a self-executing one). The return value will be
assigned to the 'myModule' global property.
- 'this.myModule || {}' is the argument passed to the self executing function.
This is a common expression that takes into account two possible situations.
If 'this.myModule' has already been assigned, it will be passed to the
function; otherwise, the function will receive an empty literal object, which
will be the initial module object. This is considered a micro-optimization.
When the global scoped objects (such as a 'document' or 'window') are passed,
it gives immediate scope so that the browser doesn't have to search through
the scope chain.
- The self-executing function content takes the 'module' object as an argument.
Then, it defines some module content (in this example, we add a 'MyClass'
definition). Finally, it returns the module itself and this is the result that is
assigned to the 'myModule' global property.
If we use this module definition for every class we need to define, in every file, we
can sleep easy because no matter how many times we call this assignment, no matter
in which order, this idiomatic syntax will add a new piece of functionality to the
module. The first time 'this.myModule' will be undefined so as to start with an empty
literal object, and from the second time onward we will reassign the 'myModule' global
object to itself, adding something new inside the self-executing function every time.
=======================================================================
JAVASCRIPT FUNCTION
*) Execution context in Javascript:
When a function is invoked, an execution context is created. The context is created with the following process:
+ The "arguments" object is created.
+ The function's "scope" is created.
+ "variables" for the function are instantiated.
+ The "this" property (for the context itself) is created. ("this" is a property of the object function)
==> "this" is the reference to the object that is considered the context (or scope) of the function's invocation.
1) Parameters:
Function arguments are the real values passed to (and received by) the function. JavaScript functions do not perform type checking on the passed arguments. JavaScript functions do not check the number of arguments received.
If a function is called with missing arguments (less than declared), the missing values are set to: undefined
We can set parameter defaults like below:
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}
Or, even simpler:
function myFunction(x, y) {
y = y || 0;
}
If a function is called with too many arguments (more than declared), these arguments cannot be referred, because they don't have a name. They can only be reached in the arguments object.
2) The "Arguments" Object
JavaScript functions have a built-in object called the "arguments" object. The argument object contains an array of the arguments used when the function was called (invoked).
Example
x = findMax(1, 123, 500, 115, 44, 88);
function findMax() {
var i, max = 0;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
Arguments are Passed by Value: if a function changes an argument's value, it does not change the parameter's original value.
Objects are Passed by Reference: if a function changes an object property, it changes the original value.
3) A function is also a variable (data):
function Person(firstName) {
this.firstName = firstName;
}
Person.prototype.sayHello = function() {
alert("Hello, I'm " + this.firstName);
};
var person1 = new Person("Alice");
var person2 = new Person("Bob");
var helloFunction = person1.sayHello; // refer to a function definition
person1.sayHello(); // alerts "Hello, I'm Alice"
person2.sayHello(); // alerts "Hello, I'm Bob"
4) Call a function by using funcName(), it does not care how much parameters you put into it:
helloFunction(); // alerts "Hello, I'm undefined" (or fails
// with a TypeError in strict mode)
alert(helloFunction === person1.sayHello); // alerts true
alert(helloFunction === Person.prototype.sayHello); // alerts true
5) Two special ways to call a function dynamically:
a) Using Function.call(theObject, parameter1, parameter2,...): fun.call(thisArg[, arg1[, arg2[, ...]]])
helloFunction.call(person1); // alerts "Hello, I'm Alice"
b) Using Function.apply(theObject, [an array of parameters]): fun.apply(thisArg, [argsArray])