为什么原型分配在这里不起作用? [英] Why is prototype assignment not working here?

查看:39
本文介绍了为什么原型分配在这里不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var foo = {
    name: "foo"
};

var bar = {};

bar.prototype = foo;

document.writeln("Bar name: " + bar.name + "<br />");

这是我在浏览器中得到的:

And here's what I got in browser:

栏名称:未定义

为什么会这样?Javascript 不应该在 bar 上查找 name,然后在 foo 上找到它吗?为什么它只是未定义?

Why is this happening? Shouldn't Javascript look up name on bar, and then go up on foo and finds it? Why is it simply undefined?

推荐答案

不幸的是,在 Javascript 中 x.prototype != "prototype of x".x.prototype 表示如果 x 是一个构造函数(=function),x.prototype 将是 new x<的原型/代码>".如果 x 不是函数,则 x.prototype 没有意义.

Unfortunately, in Javascript x.prototype != "prototype of x". x.prototype means "if x is a constructor (=function), x.prototype will be a prototype of new x". If x is not a function, x.prototype doesn't make sense.

这与语言的其余部分一样令人困惑.请记住,Eich 先生只有 10 天的时间来创建它 [ref].

This is no more and no less confusing than the rest of the language. Remember, Mr. Eich had only 10 days to create it [ref].

为了给已经创建的对象分配一个原型,ES6 (Harmony) 提供了 setPrototypeOf.在其他引擎中,有一个特定于供应商的 hack o.__proto__=....大多数情况下,这是个坏主意.

To assign a prototype to an already created object, ES6 (Harmony) offers setPrototypeOf. In other engines, there's a vendor-specific hack o.__proto__=.... Mostly, it's a bad idea.

这篇关于为什么原型分配在这里不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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