javascript 对象方法、类方法、原型方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript">
        /*
        * 1、对象方法包括构造函数中的方法以及构造函数原型上面的方法
        * 2、类方法,其实这里的类就是一个函数,在js中由于函数也是一个对象,所以可以为函数添加属性以及方法,这种方法在node中用的比较多
        * 3、原型方法一般用于对象实例共享。在原型上面添加的方法,能实现对象实例共享,这样就不用每一次初始化一个实例的时候,为其分配相应的内存了
        * */
        function FnGuo(oDiv){
            this.msg = oDiv.innerHTML;
            this.showMsg = function(){
                alert("对象方法:" + this.msg);      //对象方法
            };
        }
        FnGuo.showMsg = function(){
            alert("类方法");
        };
        FnGuo.prototype.showMsg02 = function(){
            alert("原型方法:" + this.msg);
        };
        onload = function(){    //也可以window.onload
            var oFnGuo = new FnGuo(document.getElementsByTagName('div')[0]);
            var oFnGuo02 = new FnGuo(document.getElementsByTagName('div')[1]);
            oFnGuo.showMsg();   //对象方法需要通过实例化对象去调用
            FnGuo.showMsg();    //类方法不需要通过实例化对象去调用

            oFnGuo.showMsg02();     //原型方法也需要通过实例化对象去调用
            oFnGuo02.showMsg02();   //原型方法,能实现对象实例oFnGuo和oFnGuo02共享,这两个实例的原型方法showMsg02共享内存
        };
    </script>
</head>
<body>
<div>从明天开始带薪放假半年</div>
<div>从明天开始上班</div>
</body>
</html>

 

posted @ 2017-11-03 15:54  我将枕中记忆抹去任岁月浮光掠影  阅读(155)  评论(0编辑  收藏  举报