简体   繁体   English

JavaScript新对象可以将原型链接到另一个对象

[英]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
  1. why in the body of create function why we assign F to a function 为什么在create函数的主体中为什么我们将F分配给函数
  2. and at the end return a new F() 最后返回一个新的F()
  3. why in part 3 we assign another_person to a function 为什么在第3部分中,我们将another_person分配给一个函数

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的参数分配给Fprototype 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM