您的位置:首页 > 编程语言 > Java开发

JavaScrip--JS面向对象

2020-02-02 08:36 1151 查看

一:jsOOP.js文件的编写如下:
var person={
    name:"ymt",
    age:26,
    eat:function(){
        alert("我喜欢吃米饭");
    }
}

alert("名字:"+person.name);
//这是使用函数式的方式构造对象
function personone(){

}
personone.prototype={
    name:"ymt",
    age:26,
    eat: function () {
        alert("I eat rice");
    }
}
var p=new personone();
alert(p.eat);

二:jsOOP2.js文件的编写如下:
这个文件里面牵涉到
1、封装
2、继承
3、子类重写父类的方法
4、子类调用父类的方法
代码编写如下:
(function(){
    function people(name){
        this._name=name;
    }

    people.prototype.print=function(){
        alert("people--hello");
    }
    people.prototype.printname=function(){

    }
    window.people=people;//必须使用这种方式提供一个开放的接口
}());//使用这种方式实现封装,注意:不要忘记这个分号

(function(){
    function student(){

    }
//实现了继承
    student.prototype=new people("ymt");

//实现调用父类的方法
    var peo_print=people.prototype.print;
//现在我们要定义自己的一个方法,方法的重写
    student.prototype.print=function(){
        //调用父类的方法
        peo_print.call(this);

        alert("student--hello"+this._name);//这个this._name实际上是继承了父类people的一个字段
    }
    window.student=student;//必须使用这种方式提供一个开放的接口
}());//使用这种方式实现封装,注意:不要忘记这个分号
var s=new student();
s.print();

三:jsOOP2.js文件的编写如下:
这是另一种方式实现的
1、封装
2、继承
3、子类重写父类的方法
4、子类调用父类的方法
(function(){

   function people(){
       var _this={}
       _this.print=function(){
           alert("people");
       }
       return _this;
   }

    window.people=people;
}());

(function(){

    function student(){
        var _this=people();

        var peo_print=_this.print;

        _this.print=function(){

            peo_print.call(this);

            alert("student");
        }

        return _this;
    }

    window.student=student;
}());

var s=new student();
s.print();

四:使用
<body>
//<script src="jsOOP.js">
//</script>
//<script src="jsOOP2.js">
//</script>
<script src="jsOOP3.js">
</script>
</body>

转载于:https://www.cnblogs.com/YangMT/p/4867263.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
amwxytu75574 发布了0 篇原创文章 · 获赞 0 · 访问量 103 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: