2016年5月4日 星期三

Javascript小小入門

無物件概念

文字變數

var sayHi = 'helloworld';
var sayHi = "helloworld";

數字變數

var i = 0;
var pi = 3.14;

函數

宣告+定義

var helloworld = function() {
console.log('hello world!');
};

呼叫執行

helloworld();

顯示

hello world!

有物件概念

Javascript有一個特有的特色,稱為「原型導向」,所以在此不直接定成「物件導向」

建構式

下面兩種寫法相同。
var student = new Object();
var student = {};

建構式1

宣告+定義

function human(name) {
this.name = name;
this.goto = function(place) {
console.log(this.name + ' go to ' + place);
};
};

呼叫執行

var student = new human('good student');
student.goto("school");

顯示

good student go to school


類別加上新的 Method

function human(name) {
this.name = name;
};

human.prototype.goto = function(place) {
console.log(this.name + ' go to ' + place);
};

呼叫執行

var student = new human('good student');
student.goto("school");

顯示

good student go to school



建構式2

直接建構物件

var student = {
name: 'good student',
goto: function(place) {
console.log(this.name + ' go to ' + place);
}
};

呼叫執行

student.goto("school");

顯示

good student go to school


物件加上新的 Method

var student = {
name: 'good student',
};

student.goto = function(place) {
console.log(this.name + ' go to ' + place);
};

呼叫執行

student.goto("school");

顯示

good student go to school


沒有留言:

張貼留言