JavaScript学习

javascript面向对象

初学javascript,感觉javascript的面向对象编程还是很有意思的,在此记录下来.
面向对象的三大特征:封装,继承,多态
(多态还没搞明白)

1.面向对象:定义一个对象

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:方式二,函数构造器,类似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!"


//有参数

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(){
    //调用父类的函数
    superSay.call(this);    //"Hello!"

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


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

4.封装,通过(function(){ //properties的模式 }());达到封装


(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(){
    //调用父类的函数
    superSay.call(this);    //"Hello!"

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

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

}());

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

5.另外的一种写法,面向对象:使用空对象承载成员信息


(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!"

你可能感兴趣的:(JavaScript学习)