我知道你可以用这个函数设置一个新对象的原型(prototype)( 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;
谢谢理查德
最佳答案
Summary
Creates a new object with the specified prototype object and properties.
因此,让我们看一个简单的示例,其中使用 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
Creates a new object with the specified prototype object and properties.
和新
( MDN )
[...] creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
因此,使用 Object.create
创建的实例可以获得对属性的访问权限,因为它们被其 prototype
和 new
所在的属性所遮蔽。 code> 被使用,有它自己的属性,由它的构造函数定义。
所以不,它不会创建自己的属性。 (尽管您可以传递一个对象来直接定义对象属性描述符)
关于javascript - Object.create 是否也创建自己的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15662363/