为什么new和object.create在此示例中的行为不同 [英] Why do new and object.create behave differently in this example

查看:75
本文介绍了为什么new和object.create在此示例中的行为不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个简单的示例中,为什么newObject.create的行为不同?

In this simple example, why do new and Object.create behave differently?

var test=function(name){
    this.name=name
};
var test1= new test("AAA");
test1.name;//AAA

var test2=Object.create(test);
test2.name="AAA";
typeof(test2);//Object
test2.name;//"" (empty string).

为什么test2.name为空?

推荐答案

Object.create 期望 Object 作为原型链的第一个参数,而不是 function (或您的情况下的构造函数).

Object.create expects an Object as it's first argument for the prototype chain, not a function (or constructor in your case).

如果您传递 function 不会抱怨,但这意味着您创建的 Object 将继承某些额外的内容,例如,不可写性函数名称.

It won't complain if you pass a function, but it means that certain extra things will be inherited by your created Object, for example, the non-writability of function names.

得到空字符串的原因是因为test是匿名函数,所以test.name"".就像我上面说的那样,这是不可写的,所以

The reason you're getting an empty string is because test is an anonymous function, so test.name is "". As I said above, this is non-writable, so

test.name = 'foo';
test.name; // still ""

如果您对test使用了命名的函数表达式,这将更加明显.

If you had used a named function expression for test, this would have been more obvious.

var test = function foobar() {},
    ex = Object.create(test);
ex.name; // "foobar"


编辑,对于使用Object.createtest而言,其行为类似于new的函数看起来像这样


EDIT a function that behaves like new for test using Object.create would look like this

function myNew() {
    var o = Object.create(test.prototype); // set up prototype inheritance
    test.apply(o, arguments);              // then construct
    return o;
}
// and using it
var test3 = myNew('AAA');
test3.name; // "AAA"
test3.name = 'BBB';
test3.name; // "BBB"

不能保证此模式可与DOM构造函数一起使用.

This pattern is not guaranteed to work with DOM constructors.

这篇关于为什么new和object.create在此示例中的行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆