[英]does Object.create also create own properties
我知道您可以使用此函数设置新对象的原型(请阅读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;
谢谢,理查德
摘要
用指定的原型对象和属性创建一个新对象。
因此,让我们看一个简单的示例,其中的对象用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());
现在看看控制台输出
左: new
右: Object.create
如您所见,两者都使用其属性创建了一个新的对象实例。
只有Object.create
用指定的原型对象和属性创建一个新对象。
和new
( MDN )
[...]创建用户定义的对象类型或具有构造函数的内置对象类型之一的实例。
因此,使用Object.create
创建的Instance可以访问属性,因为它们被其prototype
所遮盖,而使用new
的实例具有其自己的属性,该属性由其构造函数定义。
因此,不,它不会创建自己的属性。 (尽管您可以传递一个Object来直接定义Objects属性描述符)
是否还会创建自己的属性
如果您阅读文档 ,则表示“ 否” -除非您通过第二个参数告诉它这样做。 它的基本用途是创建一个新的空对象,并将其内部原型设置为参数。 然后,第二个参数将像defineProperties
一样工作。
如果在这样的对象文字中使用它
return Object.create(this);
我在这里看不到任何对象文字,但是由于您不使用第二个参数,因此返回的对象将没有自己的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.