javascript 为什么原型未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14545210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:55:20  来源:igfitidea点击:

why prototype is undefined

javascriptprototype

提问by Joe.wang

I known this has been asked hundreds of times, however, I can't seem to grasp the concept of prototype

我知道这已被问过数百次,但是,我似乎无法理解 prototype

Here's my sample script

这是我的示例脚本

var config = {
  writable: true,
  enumerable: true,
  configurable: true
};

var defineProperty = function(obj, name, value) {
  config.value = value;
  Object.defineProperty(obj, name, config);
}


var man= Object.create(null);
defineProperty(man, 'sex', "male");

var person = Object.create(man);
person.greet = function (person) {
    return this.name + ': Why, hello there, ' + person + '.'
}
var p=Object.getPrototypeOf(person);
alert(p.sex);//shows male
person.prototype.age=13;//why there is a error said the prototype is undefined? I thought it supposed be man object...

var child=function(){}
child.prototype.color="red";//why this line doesn't show error? both child and person are an object . 

alert(child.prototype.color);//shows red

var ch=Object.getPrototypeOf(child);

alert(ch.color);//why it is undefined? it is supposed red.

Hope you can give me some helps... thanks.

希望你能给我一些帮助...谢谢。

Updated:

更新:

Thanks your guys kindly help, Based on Elclanrs's answer, Below is what I learned.

感谢你们的帮助,根据 Elclanrs 的回答,以下是我学到的。

Functionis the one of the build-in objects in javascript. the 3 format creation function object are equal.

Function是 javascript 中的内置对象之一。3种格式创建函数对象是相等的。

var function_name = new Function(arg1, arg2, ..., argN, function_body)
function function_name(arg1, arg2, ..., argN)
{
...
}
var function_name=function(arg1, arg2, ..., argN)
{
...
}

So, that is why create a prototype chain we have to create a function and then call it with the new keyword .

所以,这就是为什么创建一个原型链我们必须创建一个函数,然后用 new 关键字调用它。

Function.prototypeis the reference to All the Function object prototype.

Function.prototype是对 All Function 对象的引用prototype

Cheers

干杯

采纳答案by elclanrs

I think you might be mixing concepts. Try grasping the concept of prototypes with classic prototype inheritance first, then you can get into all the new Objectstuff.

我想你可能会混淆概念。首先尝试通过经典原型继承来掌握原型的概念,然后才能进入所有新Object事物。

In JavaScript, every object (numbers, strings, objects, functions, arrays, regex, dates...) has a prototypewhich you can think of as a collection of methods (functions) that are common to allcurrent and future instances of that object.

在 JavaScript 中,每个对象(数字、字符串、对象、函数、数组、正则表达式、日期...)都有一个prototype,您可以将其视为该对象所有当前和未来实例通用的方法(函数)的集合.

To create a prototype chain you have to create a function and then call it with the newkeyword to specify that it is a constructor. You can think of constructors as the main function that takes the parameters necessary to build new instances of your object.

要创建原型链,您必须创建一个函数,然后使用new关键字调用它以指定它是一个构造函数。您可以将构造函数视为主函数,它接受构建对象新实例所需的参数。

Having this in mind, you can extend native objects or create your own new prototype chains. This is similar to the concept of classes but much more powerful in practice.

考虑到这一点,您可以扩展本机对象或创建自己的新原型链。这类似于类的概念,但在实践中更强大。

Similar to your example, you could write a prototype chain like this:

与您的示例类似,您可以编写这样的原型链:

// Very basic helper to extend prototypes of objects
// I'm attaching this method to the Function prototype
// so it'll be available for every function
Function.prototype.inherits = function(parent) {
  this.prototype = Object.create(parent.prototype);
}

// Person constructor
function Person(name, age, sex) {
  // Common to all Persons
  this.name = name;
  this.age = age;
  this.sex = sex;
}

Person.prototype = {
  // common to all Persons
  say: function(words) {
    return this.name +'says: '+ words;
  }
};

// Student constructor   
function Student(name, age, sex, school) {
  // Set the variables on the parent object Person
  // using Student as a context.
  // This is similar to what other laguanges call 'super'
  Person.call(this, name, age, sex);
  this.school = school; // unique to Student
}

Student.inherits(Person); // inherit the prototype of Person

var mike = new Student('Mike', 25, 'male', 'Downtown'); // create new student

console.log(mike.say('hello world')); //=> "Mike says: hello world"

In newer version of JavaScript (read EcmaScript) they added new ways to deal with objects and extend them. But the concept it's a bit different from classical prototype inheritance, it seems more complicated, and some more knowledge of how JS works underneath would help to really understand how it works, plus it doesn't work in older browsers. That's why I suggest you start with the classical pattern for which you'll find accurate and abundant information on the internet.

在较新版本的 JavaScript(阅读 EcmaScript)中,他们添加了处理对象和扩展对象的新方法。但是它的概念与经典的原型继承有点不同,它看起来更复杂,更多地了解 JS 在底层如何工作将有助于真正理解它是如何工作的,而且它在旧浏览器中不起作用。这就是为什么我建议您从经典模式开始,您可以在互联网上找到准确而丰富的信息。

回答by Aadit M Shah

The prototypeproperty only exists on functions, and personis not a function. It's an object.

prototype属性仅存在于函数上,而person不是函数。这是一个object.

Here's what's happening:

这是发生了什么:

var man = Object.create(null);         // man (object) -> null
man.sex = "male";

var person = Object.create(man);       // person (object) -> man (object) -> null
person.greet = function () { ... };

var p = Object.getPrototypeOf(person); // man (object) -> null
alert(p.sex);                          // p is the same object as man

person.prototype.age = 13;             // person doesn't have a prototype

var child = function () {};            // child (function) -> Function.prototype
                                       // -> Object.prototype -> null
child.prototype.color = "red";         // child has a prototype

var ch = Object.getPrototypeOf(child); // Function.prototype

alert(ch.color);                       // ch is not the same as color.prototype
                                       // ch is Function.prototype

For more information I suggest you read this answer: https://stackoverflow.com/a/8096017/783743

有关更多信息,我建议您阅读此答案:https: //stackoverflow.com/a/8096017/783743

Edit:To explain what's happening in as few words as possible:

编辑:用尽可能少的词来解释正在发生的事情:

  1. Everything in JavaScript is an object except primitive values (booleans, numbers and strings), and nulland undefined.

  2. All objects have a property called [[proto]]which is not accessible to the programmer. However most engines make this property accessible as __proto__.

  3. When you create an object like var o = { a: false, b: "something", ... }then o.__proto__is Object.prototype.

  4. When you create an object like var o = Object.create(something)then o.__proto__is something.

  5. When you create an object like var o = new f(a, b, ...)then o.__proto__is f.prototype.

  6. When JavaScript can't find a property on oit searches for the property on o.__proto__and then o.__proto__.__proto__etc until it either finds the property or the proto chain ends in null(in which case the property is undefined).

  7. Finally, Object.getPrototypeOf(o)returns o.__proto__and not o.prototype- __proto__exists on all objects including functions but prototypeonly exists on functions.

  1. JavaScript 中的一切都是对象,除了原始值(布尔值、数字和字符串)和nullundefined

  2. 所有对象都有一个称为[[proto]]程序员无法访问的属性。然而,大多数引擎都将此属性作为__proto__.

  3. 当你创建一个对象一样var o = { a: false, b: "something", ... },然后o.__proto__Object.prototype

  4. 当你创建一个对象一样var o = Object.create(something),然后o.__proto__something

  5. 当你创建一个对象一样var o = new f(a, b, ...),然后o.__proto__f.prototype

  6. 当 JavaScript 无法在o其上找到属性时,将搜索属性 on o.__proto__,然后o.__proto__.__proto__等等,直到它找到该属性或原型链以 结束null(在这种情况下,该属性是undefined)。

  7. 最后,Object.getPrototypeOf(o)返回o.__proto__和 not o.prototype-__proto__存在于包括函数在内的所有对象上,但prototype仅存在于函数上。