JavaScript學(xué)習(xí)

javascript面向?qū)ο?/h2>

初學(xué)javascript,感覺javascript的面向?qū)ο缶幊踢€是很有意思的,在此記錄下來.
面向?qū)ο蟮娜筇卣?封裝,繼承,多態(tài)
(多態(tài)還沒搞明白)

1.面向?qū)ο?定義一個對象

1.1:方式一,直接{ }


var Person = {
    //properties
    name:"myNmae",
    age:12,
    eat:function(){
        console.log("I'm eating!");
    }
}
//訪問

Person.name;    //myNmae
Person.age; //12
Person.eat(); //"I'm eating"


1.2:方式二,函數(shù)構(gòu)造器,類似class的概念


//無參
function Person(){

}

Person.prototype = {
    name:"myNmae",
    age:12,
    run:function(){
        console.log("I'm running!");
    }
}

//實例化

var p = new Person();

//訪問
p.name; //myName
p.age;      //12
p.run();    //"I'm running!"


//有參數(shù)

function Person1(name){
    this._name = name;
}

Person1.prototype = {
    age : 13
}


2.javascript的繼承


function People(){

}

People.prototype.say = function(){
    console.log("Hello!");
}

//Student繼承于People

function Student(){

}

Student.prototype = new People();

var stu = new Student();

stu.say();  //"Hello!"

3.重寫


function People(){

}

People.prototype.say = function(){
    console.log("Hello!");
}

//Student繼承于People

function Student(){

}

Student.prototype = new People();

var superSay = Student.prototype.say;

Student.prototype.say = function(){
    //調(diào)用父類的函數(shù)
    superSay.call(this);    //"Hello!"

    console.log(" student say hello!");
}


var stu = new Student();
stu.say();  //"Hello!" + "student say hello!"

4.封裝,通過(function(){ //properties的模式 }());達(dá)到封裝


(function(){

    var secret = "secret"; //外面不能直接訪問這個成員

    function People(){

}

People.prototype.say = function(){
    console.log("Hello!");
}


//對外接口
window.People = People;
}());


;


(function(){
    //Student繼承于People

function Student(){

}

Student.prototype = new People();

var superSay = Student.prototype.say;

Student.prototype.say = function(){
    //調(diào)用父類的函數(shù)
    superSay.call(this);    //"Hello!"

    console.log(" student say hello!");
}

//對外的接口
window.Student = Student;

}());

var stu = new Student();
stu.say();  //"Hello!" + "student say hello!"

5.另外的一種寫法,面向?qū)ο?使用空對象承載成員信息


(function(){
    function Person(){
    _this = {};
    _this.sayHello = function(){
        alert("Hello");
    }
    
    return _this;
    
}

window.Person = Person;

}());





//繼承

(function(){
    function Teacher(){
    var _this = Person();
    
    //重寫
    var superSay = _this.sayHello;
    
    _this.sayHello = function(){
    superSay.call(_this);
        alert("Haha!");
    }
    
    return _this;
}

window.Teacher = Teacher;

}());

var t = Teacher();
t.sayHello();   //"Hello" + "Haha!"

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容