標籤:style 方式 world 關心 運算式 on() script 自訂對象 aaa
對象有三種:內建對象,DOM對象,自訂對象
那函數是什麼類型,先看這樣一段代碼
function fn(){
alert(‘hello world‘);
}
fn();
先聲明,在調用,成功運行
var fn = function(){
alert(‘hello world‘);
};
fn();
先聲明,在調用,成功運行
fn();
function fn(){
alert(‘hello world‘);
}
再看這段代碼,按照js是從上向下執行的規則,函數先調用再聲明是不行的,但這段代碼運行後也成功彈出了hello world.
fn();
var fn = function(){
alert(‘hello world‘);
};
報錯,提示fn is not a function
原因是
function fn(){}叫函數的聲明,var fn = function(){}叫做函數的運算式.函數的運算式必須先聲明再調用,但函數的聲明特殊在可以先調用再聲明,js引擎在解析js代碼時會先檢測有多少這樣的函數,然後把它提前聲明
函數是不是對象?我們typeof一下發現是function,那function不是一個對象麼?關於函數其實有標準的寫法:
var fn = function(){
alert(hello world);
}
寫成var fn = new Function(“alert(hello world);”)
這時的typeof雖然是function 但在js中凡是new出來的都可以算作對象.此時,函數便可以算作一個對象了
對象直接量:
在js中,我們可以寫出如下代碼
var o = new Object();
o.name = ‘lisi‘;
o.sayhello = function(){
alert(hello);
}
其實還有一種更為直觀的寫法,被稱作對象直接量
var o = {
name:‘lisi‘,
sayhello:function(){}
}
o.sayhello();
這種方式更為簡單和直觀,相當於把一些屬性方法都封裝到一個對象裡,在接下來的編程我將只關心這個對象即可
類:具有相同方法和屬性的對象的集合
例:function Cat(name,age){
this.name = name,
this.age = age
}
Cat.prototype.eat = function(){
console(aaa);
}
var cat1 = New Cat(‘mimi’,3);
cat1.eat();
將屬性封裝到類裡,將方法封裝到原型prototype中
在es6中可以直接用class關鍵字
javascript物件導向