javascript物件導向

來源:互聯網
上載者:User

標籤: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物件導向

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.