如何使用object.create创建对象

How to create object using object.create?

本文关键字:创建对象 create object 何使用      更新时间:2023-09-26

>我在用标签引用的单独文件中有以下代码

function _TEST()
     {
      var val; 
      this.get = function(x)
           {
            return val;
           }
      this.prop = 'testing';
      this.set = function(x)
           {
            val = x
            return val;
           }
      this.exp = function(x)
          {
            function meth(x)
               {
                return 'I am a private '+x;
               }
           return meth(x);
          }
     }

现在在主页的头部部分,我有

var tst = new _TEST();
window.onload = function()
   {
    tst.set('Hello')
    alert(tst.get());
    var tst2 = Object.create(_TEST.prototype);
        tst2.prop = "testing"; // the only property that shows up for tst2 below
    var str = '';
    for(var x in tst)
      {
       str += x+" : "+tst[x]+"'n";
      }
    str += "'n'ntst2:'n"
    for(var x in tst2)
      {
       str += x+" : "+tst2[x]+"'n";
      }
    alert(str)
   }

调用警报的输出为:

get : function (x) {
return val;
 }
 prop : testing
 set : function (x) {
   val = x;
   return val;
}
exp : function (x) {
function meth(x) {
    return "I am a private " + x;
}
return meth(x);
}

tst2:
prop : testing

据我了解,Object.create 假设创建一个继承自原型的对象独立。但是TST2没有这些。我在这里做错了什么?这正在Mac OSX上的Firefox 12.0中进行测试,我不确定它使用的javascript版本。我是使用 O'Reillies Javascript: The Definitive Guide (rhino book) 来增加我对对象和相关知识法典

编辑:我想通了:

它适用于

var tst2 = Object.create(tst);

您的代码尚未向_TEST.prototype添加任何属性。_TEST函数将属性直接添加到进行new _TEST()调用时创建的每个实例。这与原型无关。