[英]JavaScript-new object can have prototype link to another object
I have 3 questions about the following code that I have found in a text book about JavaScript called "JavaScript: The Good Parts". 在关于JavaScript的教科书中,我找到了三个有关以下代码的问题,这些代码叫做“ JavaScript:好的零件”。
It says that when we make a new object, we can select the object that should be its prototype. 它说,当我们创建一个新对象时,我们可以选择应该作为其原型的对象。
Part 1: lets say we have the following object 第1部分:假设我们有以下对象
var person = {
first_name: "Tim",
last_name: "Thompson",
middel_name: "Jack",
nick_name: "GoldTeeth",
age:30
};
Part 2: then we are going to add the Create function to Object using following code 第2部分:然后,我们将使用以下代码将Create函数添加到Object
Object.create = function(o){
var F = function(){};
F.prototype = o;
return new F();
}
and then later we can map any new object's prototype to "person" using Object.create()
function 然后,我们可以使用
Object.create()
函数将任何新对象的原型映射到“人”
part 3: example// 第3部分:示例//
var another_person = Object.create(person);
alert(another_person.first_name); //Tim
I understand that in JavaScript functions are object but I can't follow the logic. 我了解JavaScript函数中的对象是对象,但我不能遵循逻辑。 Could anyone help me?
有人可以帮我吗?
When you have a code like this: 当您有这样的代码时:
var foo = bar;
then your variable called foo
will get the value bar
. 然后您的名为
foo
的变量将获得值 bar
。 So it is bar
assigned to foo
, not foo
assigned to bar
, therefore you have some misconceptions in your question. 所以它是
bar
分配给foo
, 而不是 foo
分配给bar
,因此您在问题中存在一些误解。
As about the code posted. 至于代码发布。 The first part creates an object and assigns it to
person
. 第一部分创建一个对象并将其分配给
person
。 The second part assigns a function to Object.create
. 第二部
Object.create
分配一个函数。 The function creates a new empty function and assigns it to F
. 该函数创建一个新的空函数并将其分配给
F
When this is done, the parameter called o
is assigned to F
's prototype
. 完成此操作后,将名为
o
的参数分配给F
的prototype
。 Since F
has a prototype
, it can be instantiated and a new instance of F
is returned. 由于
F
具有prototype
,因此可以实例化它并返回F
的新实例。 The third part is a test code. 第三部分是测试代码。 It takes
person
and using Object.create
instantiates a new person
. 它需要
person
并且使用Object.create
实例化一个新person
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.