JavaScript - 面向对象

基本面向对象

 var person = {
     name: "w",
     age : 30,
     eat: function(){
         alert(1);
     }
 }


 alert(person.name);
 person.eat;

 

函数构造器

function Person(){

}

Person.prototype = {
    name: "a",
    age: 30,
    eat: function (){
        alert(1);
    }
}

var p = new Person();

p.age
p.name;
p.eat();

 

 

JavaScript 不存在类的概念, 可以用 function 来模拟

function Person(){

}

Person.prototype.eat = {
    alert(1);
}



// 继承
function Student(){

}

Student.prototype = new People();

var s = new Student()

s.say()

 

 

/* Parent */
function Person(){

}

Person.prototype.eat = {
    alert(1);
}

/* Child */
function Student(){

}

Student.prototype = new People();

var super = Student.prototype.eat;

Student.prototype.eat = function (){
    //  调用父类的方法
    super.call(this);
}

 

 

 

成员的索引

/* Parent */
function Person(name){
    this._name = name;
}

Person.prototype.eat = {
    alert(this._name);
}

/* Child */
function Student(name){
    this._name = name;
}

Student.prototype = new People();

Student.prototype.eat = function (){
    alert(this._name);
}

var s = new Student("name");
s.say();

 

 

封装

// 封装
(function(){
    // 只能在内部访问
    var fd = 0;
    /* Parent */
    function Person(name){
        this._name = name;
    }

    Person.prototype.eat = {
        alert(this._name);
    }
  
  // 外部访问接口
  window.People = People; }());


 

posted @ 2015-12-06 19:45  `Laimic  阅读(119)  评论(0)    收藏  举报