开发者社区> 问答> 正文

Javascript面向对象编程

<html>
<head>
<style>
span{color:red;}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<script>
//定义了一个对象
var obj1 = {
  init0:"1-0",
    init1:function(){ return "1-1"; },
    init2:function(){   return "1-2"; }
};
document.write("<span>obj1:</span>" + obj1 + "<br />");
document.write("<span>obj1.init0:</span>" + obj1.init0 + "<br />");
document.write("<span>obj1.init1:</span>" + obj1.init1 + "<br />");
document.write("<span>obj1.init2():</span>" + obj1.init2() + "<br />");
document.write("<br />");
//
var obj2 = function(){
    init0 = "2-0";
    return{
        init1:function(){   return "2-1"; },
        init2:function(){   return "2-2"; }
    }
  init3:"2-3";
}();
document.write("<span>obj2:</span>" + obj2 + "<br />");
document.write("<span>obj2.init0:</span>" + obj2.init0 + "<br />");
document.write("<span>obj2.init1:</span>" + obj2.init1 + "<br />");
document.write("<span>obj2.init2():</span>" + obj2.init2() + "<br />");
document.write("<span>obj2.init3:</span>" + obj2.init3 + "<br />");
document.write("<span>obj2.init3():</span>" +'这样写会出错' + "<br />");
document.write("<br />");
//
var obj3 = function(){
    init0 = "3-0";
    return{
        init1:function(){   return "3-1"; },
        init2:function(){   return "3-2"; }
    }
};
document.write("<span>obj3:</span>" + obj3 + "<br />");
document.write("<span>obj3.init0:</span>" + obj3.init0 + "<br />");
document.write("<span>obj3.init1:</span>" + obj3.init1 + "<br />");
document.write("<span>obj3.init2():</span>" + '这样写会出错' + "<br />");
document.write("<br />");
//
var obj4 = function(){
    init0 = "4-0";
    return sobj = {
        init1:function(){   return "4-1"; },
        init2:function(){   return "4-2"; }
    }
};
document.write("<span>obj4:</span>" + obj4 + "<br />");
document.write("<span>obj4.init1:</span>" + obj4.init1 + "<br />");
document.write("<span>obj4.sobj.init2:</span>" + '这样写会出错' + "<br />");
document.write("<span>obj4.sobj.init2():</span>" + '这样写会出错' + "<br />");
</script>
</body>
</html>

展开
收起
a123456678 2016-07-15 14:51:48 1929 0
1 条回答
写回答
取消 提交回答
  • obj2.init3出错

    是因为obj2实际是等于你的方法的执行的结果,也就是:

    {

    init1:function(){ return "2-1"; },

    init2:function(){ return "2-2"; }

    }

    自然没有init3。

    obj3.init1出错,是因为obj3是方法对象的引用,他是访问不到你的init1的。

    obj4.init1出错的原因和obj3.init1一样。

    另外,貌似obj3.init0也应该访问不到。

    2019-07-17 19:56:59
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
JavaScript函数 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载