JavaScript面向对象学习小结

1,javascript中没有类的概念,是用function来模拟类;

如声明类:function People(){  }

2,声明方法时,People.prototype.say = function(){  alert("hello");  }

如function Student(){   }

Student.prototype = new People();  //student扩展自people,

var s = new Student(); 

s.say(); //若扩展成功,则可以实现say方法;调用的是父类People的say方法;

3,Student.prototype.say = new function(){   alert("stu-hello");  } //子类复写父类的方法,

var s = new Student();

s.say();  //调用的是子类自己的方法;

4,子类想要调用父类的say方法,

var superSay = Student.prototype.say;

Student.prototype.say = function(){

  superSay.call(this);//使用call来调用,弹出的就是父类中的hello;

  alert("stu-hello");

}

5,若在父类中的方法里传入了参数,则也要在子类的方法里传参数;

function People(name){

  this._name = name;

}

function Student(name){

  this._name = name;

}

 People.prototype.say = function(){

  alert("peo-hello"+this._name);

}

Student.prototype.say = function(){

  alert("stu-hello"+this._name);

}

6,实现封装:用小括号括起来

(function(){

  //所有操作

  function People(){  }

  People.prototype.say = function(){  alert("hello");  }

   window.People = People; //封装之后,在外部引用这个方法的话要添加这种接口;否则引用不了

}()   //要加分号

 封装的步骤:先是小括号,在小括号里添加一个function(){},在function的主体里加上所要执行的操作,最后在大括号外再加一个小括号,是代表执行的意思。

7,另一种方式阐述面向对象:

function Person() {

  var _this = {}; //声明一个空的对象

  _this.sayHello = function(){

    alert("Phello");

  }

  return _this;  //要返回_this;

}

function Teacher(){

  var _this = Person();   //通过将Person赋给_this;达到Teacher也可以调用父类方法的目的;

  var superSay = _this.sayHello;  //想要调用父类 的方法,先赋个值,再利用call;

  _this.sayHello = function(){  

    superSay.call();

    alert("Thello");   

   }   

  return _this;

}

var t = Teacher();

t.sayHello();