JS 面向对象


什么是对象:

1、面向对象的概念:

1): 一切事物皆对象

2): 对象具有封装和继承特性

3): 信息隐藏

第一种创建对象的方法

 //基本面向对象
var person={
   name:"jwen",
   age:30,
   eat:function () {
       alert("can eat");
   }
};

第二种

//函数构造器构造对象
(function () {
   function Person(name) {
       this._name = name;
   }

   Person.prototype.say = function () {
       alert("person-say()"+this._name);
   };
   window.Person = Person;
}());

//Student继承person
(function () {
   function Student(name) {
       this._name = name;
   }
   Student.prototype = new Person();//继承
   var superSsay = Student.prototype.say;
   Student.prototype.say = function () { //创建自己的say()
       superSsay.call(this);//调用父类的say()
       alert("student_say()"+this._name);
   };
   window.Student = Student;
}());

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

第三种

(function () {
   function Person(name) {
       var _this = {};
       _this._name = name;
       _this.say = function () {
           alert("Person-say()");
       };
       return _this;
   }
   window.Person = Person;
}());


function Student(name) {
   var _this = Person(name);
   var supperSay = _this.say;
   _this.say = function () {
       supperSay.call(_this);
       alert("Student-say()"+_this._name);
   };
   return _this;
}
var s = Student("Tom");
s.say();