js -- 面向对象

一:构造对象 属性和方法

<script>
        //方法一 定义对象属性和方法
        var person = {
            name : "wu",
            age : 22,
            eat : function(){
                alert("eat");
            }
        };
        alert(person.eat()); //alert : eat undifined
</script>
<script>
        //函数构造器构造对象
        function Person(){};
        Person.prototype = {
            name : "wu",
            age : 22,
            eat : function(){
                alert("eat");
            }
        };
        var p = new Person();
        alert(p.name);       //alert wu
</script>

 

二:面对对象 复写 继承 封装

<script>
        //面向对象中 js创建一个类
        function People(name) {
            this.name = name;
        };
        People.prototype.say = function(){
            alert("pre-hello" + this.name);
        };
        //Student 继承 People
        function Student(name) {
            this.name = name;
        };
        Student.prototype = new People();
        //调用父类的 say方法
        var superSay = Student.prototype.say; //注意
        //复写 父类的方法
        Student.prototype.say = function() {
            superSay.call(this);
            alert("stu-hello" + this.name);
        }
        var s = new Student("w");
        s.say();          //alert stu-hello
        /*
        //调用People 的 say方法
        var s = new Student();
        s.say();             //alert hello
        */
</script>

封装

<script>
        (function () {
            var n = "123";
            function People(name) {
                this.name = name;
            };
            People.prototype.say = function () {
                alert("pre-hello" + this.name + n);
            };
            //给其他 类 一个接口
            window.People = People;
        }());

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

            var superSay = Student.prototype.say;

            Student.prototype.say = function () {
                superSay.call(this);
                alert("stu-hello" + this.name);
            }
            window.Student = Student;
        }());
        var s = new Student("w");
        s.say();             //alert pre-hellow123  stu-hellow
</script>

 面向对象 方法二:

<script>
        function Person(name){
            //创建空的对象
            var _this = {};
            _this.name = name;
            _this.sayHello = function() {
                alert("P-hello" + _this.name);
            };
            return _this;
        };
        //继承Person
        function Teacher(name){
            var _this = Person(name);
            //父类的sayHello方法
            var superSay = _this.sayHello;
            //复写
            _this.sayHello = function(){
                superSay.call(this);
                alert("T-hello" + _this.name);
            }
            return _this;
        }
        var t = new Teacher("wu");
        t.sayHello();
</script>

 

posted @ 2018-05-15 14:01  wuyueping  阅读(135)  评论(0编辑  收藏  举报