JavaScript面向对象

  • 认识面向对象
  • 基本面向对象
  • 函数构造器构造对象
  • 深入JavaScript面向对象

认识面向对象

JavaScript面向对象_第1张图片
面向对象.png
var person= {
    name:"man",
    age:30,
    eat:function () {
        alert("能吃");
    }
}
alert(person.name);

函数构造器构造对象

Person.prototype={
   name:"manman",
   age:30,
    eat:function () {
        alert("我在吃");
    }

}
var p = new Person();

深入JavaScript面向对象

prototype 属性使您有能力向对象添加属性和方法
function People(name) {

        this.name = name;
    }
    People.prototype.say = function () {

        alert("nyye"+this.name);
    }

继承
Student.prototype = new People();

    var superSay = Student.prototype.say;

//重写父类的方法,子类重新实现
    Student.prototype.say = function () {
        superSay.call(this);//子类重写方法里调用父类方法
        alert("stusay"+this.name);
    }
采用闭包封装
(function () {

    // var n = "iwen";
    function People(name) {

        this.name = name;
    }
    People.prototype.say = function () {

        alert("nyye"+this.name);
    }
    window.People = People; //暴露接口,便于外部访问。
}()); //最后面这个括号是为了方法能够执行

(function () {
    function Student(name) {
        this.name =  name;
    }
//js 的继承
    Student.prototype = new People();

    var superSay = Student.prototype.say;

//重写父类的方法,子类重新实现
    Student.prototype.say = function () {
        superSay.call(this);//子类重写方法里调用父类方法
        alert("stusay"+this.name);
    }
    window.Student =Student;
}());

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

创建

(function () {
    function Person(name) {
        var n = "hahhaha"
        var _this ={}//空对象
        _this.name = name;
        _this.sayHello = function () {
            alert("Hello"+_this.name + n);

        }
        return _this;
    }
    window.Person= Person;
}())
function Teacher(name) {

    var _this = Person(name);
    var superSay = _this.sayHello;
    _this.sayHello = function () {
        superSay.call(_this);
        alert("PHello"+_this.name);
    }
    return _this;

}
var t  =  Teacher("manman");
t.sayHello();

你可能感兴趣的:(JavaScript面向对象)