Object.create也创建自己的属性

时间:2013-03-27 15:12:43

标签: javascript inheritance

我知道你可以用这个函数设置一个新对象的原型(read mozzilla docu) 但如果在像

这样的对象文字中使用它,它也会创建自己的属性
return Object.create(this);

我也知道这个方法来自Klass文字只复制实例方法

var subclass = function() { };
subclass.prototype = parent.prototype;
klass.prototype = new subclass;

我最感兴趣的是object.create方法

修改

  var Klass = {
  init: function(){},

  prototype: {
    init: function(){}
  },

  create: function(){
    var object = Object.create(this);
    console.log('object with class create');
    console.log(object);
    console.log("object's parent is this");
    console.log(this);
    object.parent = this;
    object.init.apply(object, arguments);
    console.log('returned object from create');
    console.log(object);
    return object;
  },

  inst: function(){
    var instance = Object.create(this.prototype);
    console.log('de instance na object create');
    console.log(instance);
    instance.parent = this;
    instance.init.apply(instance, arguments);
    console.log('arguments in inst');
    console.log(arguments);
    return instance;
  },

  proxy: function(func){
    var thisObject = this;
    return(function(){ 
      return func.apply(thisObject, arguments); 
    });
  },

  include: function(obj){
    var included = obj.included || obj.setup;
    for(var i in obj)
      this.fn[i] = obj[i];
    if (included) included(this);
  },

  extend: function(obj){
    var extended = obj.extended || obj.setup;
    for(var i in obj)
      this[i] = obj[i];
    if (extended) extended(this);
  }
};

Klass.fn = Klass.prototype;
Klass.fn.proxy = Klass.proxy;
谢谢,理查德

2 个答案:

答案 0 :(得分:2)

MDN Object.create

  

摘要

     

使用指定的原型对象和属性创建一个新对象。

让我们看一个简单的例子,其中一个Object使用new关键字进行实例化,另一个使用Object.create;

function objectDotCreate() {
    this.property = "is defined";
    this.createMe = function () {
        return Object.create(this);
    };
}
var myTestObject = new objectDotCreate();
console.log(myTestObject, myTestObject.createMe());

JSBin

现在看一下控制台输出

Console Output

左:new右:Object.create

正如您所看到的,它们都创建了一个新的Object实例及其属性。

Object.create

  

使用指定的原型对象和属性创建一个新对象。

newMDN

  

[...]创建一个用户定义的对象类型的实例,或者一个具有构造函数的内置对象类型的实例。

因此,使用Object.create创建的实例可以获得对属性的访问权限,因为它们被prototype遮蔽,而new使用的属性有自己的属性,已定义由它的构造函数。

所以不,它不会创建自己的属性。 (尽管您可以传递一个Object来直接定义Objects属性描述符)

答案 1 :(得分:1)

  

它是否也创建了自己的属性

如果您阅读docs,则说明 - 除非您告诉它使用第二个参数执行此操作。它的基本用途是创建一个 new,empty 对象,并将其内部原型设置为参数。第二个参数就像defineProperties那样。

  

如果它在像这样的对象文字中使用

     

return Object.create(this);

我在这里看不到任何对象文字,但由于你没有使用第二个参数,返回的对象将没有自己的属性。

相关问题