gpt4 book ai didi

javascript - Object.getPrototypeOf() 混淆

转载 作者:搜寻专家 更新时间:2023-11-01 04:58:12 25 4
gpt4 key购买 nike

Object.getPrototypeOf(obj) 是如何工作的?

根据定义,Object.getPrototypeOf(obj) 应该返回对象的原型(prototype)属性,或者以其他方式返回与 obj.constructor.prototype 相同的属性。

用 new 创建的对象使用其构造函数的 prototype 属性的值作为其原型(prototype)。

举个例子:

>element = document.getElementById("test")

>a = Object.getPrototypeOf(element)
HTMLDivElement

假设 HTMLDivElement 是元素的原型(prototype)。

>a.constructor.prototype
HTMLDivElement

所以 a.constructor.prototype 是 HTMLDivElement 所以 Object.getPrototypeOf(a) 应该返回 HTMLDivElement 但它返回 HTMLElement。我对 getPrototypeOf() 的定义完全感到困惑。

>b = Object.getPrototypeOf(a)

HTMLElement ----> 为什么? a.constructor.prototype 是 HTMLDivElement

实际上它返回的是原型(prototype)的 proto 属性,按照 getPrototypeOf() 的定义是不是错了?

>a.constructor.prototype.__proto__
HTMLElement

最佳答案

引自 https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Inheritance_Revisited

JavaScript is a bit confusing for developers coming from Java or C++, as it's all dynamic, all runtime, and it has no classes at all. It's all just instances (objects). Even the "classes" we simulate are just a function object.


请注意,原型(prototype)也是一个对象,因此它也可以拥有自己独特的原型(prototype)

所以让你感到困惑的代码看起来像这样

a = Object.getPrototypeOf(element)
b = Object.getPrototypeOf(a)

可以翻译成这样

a = element.__proto__
b = element.__ptoto__.__proto__

我认为现在很清楚 a != b


1) JavaScript 中的每个对象都有一个原型(prototype),您可以通过__proto__ 属性访问它

2) Function在Javascript中也是一个object

3) 函数也有一个prototype属性

4) 我们可以通过使用关键字new调用函数在JavaScript中创建对象

4) 函数 prototypeinitial __proto__ 由它们创建的任何对象


要创建新对象,我们可以这样写

//here we define a function
function SomeFunctionThatCreateObject() {
this.someStringProperty = "blablabla";
}

var obj = new SomeFunctionThatCreateObject(); //we create new object with function

var p = Object.getPrototypeOf(obj);

这段代码等同于此

var SomeFunctionThatCreateObject = function(@this) {
@this.someStringProperty = "blablabla";
return @this;
};

SomeFunctionThatCreateObject.prototype = {}; //note that prototype is also an object

var obj = {};

obj = SomeFunctionThatCreateObject(obj);

obj.constructor = SomeFunctionThatCreateObject;

obj.__proto__ = SomeFunctionThatCreateObject.prototype;

var p = obj.__proto__;

PS: 也读过这个 https://stackoverflow.com/a/9220317/474290和这个 https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Inheritance_Revisited

关于javascript - Object.getPrototypeOf() 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10013544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com