您的位置:首页 > Web前端 > JavaScript

codecademy.com之JavaScript学习

2014-02-15 15:22 429 查看
如何学习javascritpt http://javascriptissexy.com/how-to-learn-javascript-properly/
javascript学习站点 http://www.codecademy.com/zh/tracks/javascript

Data Structures

Data Types: numbers, strings, booleans and arrays.

Boolean

若没有设置或者设置为0,-0,null,"",false,undefined,NaN时为false,其他情况为true

Arrays

var myCars=new Array();
var myCars=new Array("Saab","Volvo","BMW");
var myCars=["Saab","Volvo","BMW"];
Objects

创建对象两种方式

(1)object literal notation

var myObj = {
type: 'fancy',age:24,
speak: function(){}   //method
};


(2)object constructor

var myObj = new Object(); //using a built-in constructor called Object
myObj["name"] = "Charlie";
myObj.name = "Charlie";

自定义的构造函数

function Rabbit(adjective) {
this.adjective = adjective;
var age=12; //private 不能用this修饰
this.describeMyself = function() {
console.log("I am a " + this.adjective + " rabbit");
};
}
var rabbit1 = new Rabbit("fluffy");
//className.prototype.newMethod = function(){} 给某个类添加方法
Rabbit.prototype.describeMyself = function (){}

Object Oriented

继承

// the original Animal class and sayName method
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};

// define a Penguin class
function Penguin(name) {
this.name = name;
this.numLegs = 2;
}
// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();
var p =new Penguin("Timmy");
p.sayName();
自定义声明的类都继承自Object类

//Object.prototype itself is an object
// what is this "Object.prototype" anyway...?
var prototypeType = typeof Object.prototype;
console.log(prototypeType); //object
// now let's examine it!
var hasOwn = Object.prototype.hasOwnProperty("hasOwnProperty");
console.log(hasOwn); //true
私有化成员和方法

/*
Public properties can be accessed from outside the class
Private properties can only be accessed from within the class
*/
function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;  //var this.bankBalance  (不能加this)

var returnBalance = function() {
return bankBalance;
};
// create the new function here
this.askTeller = function (){
return returnBalance;
}
}
var john = new Person('John','Smith',30);
console.log(john.returnBalance);
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: