Object.getPrototypeOf()
方法返回指定对象的原型。
示例
const obj = {id: 711};
// find the the prototype of obj
console.log(Object.getPrototypeOf(obj));
// Output: {}
getPrototypeOf() 语法
getPrototypeOf()
方法的语法是
Object.getPrototypeOf(obj)
这里,getPrototypeOf()
是一个静态方法。因此,我们需要使用类名 Object
来访问该方法。
getPrototypeOf() 参数
getPrototypeOf()
方法接受
- obj - 要返回其原型的对象。
getPrototypeOf() 返回值
getPrototypeOf()
方法返回
- 给定对象的原型。
- 如果没有任何继承的属性,则返回
null
。
注意:在 ES5 中,如果 obj 参数不是一个对象,getPrototypeOf()
方法会抛出 TypeError 异常。但是,自 ES2015 起,该参数将被强制转换为 Object
,不会抛出任何异常。
示例 1:Javascript Object.getPrototypeOf()
// create an object named person
let person = {
name: "Vincent",
age: 56,
}
// get the prototype of person object
console.log(Object.getPrototypeOf(person))
// Output: {}
在此示例中,我们创建了一个名为 person 的自定义对象。然后,我们使用 getPrototypeOf()
方法打印其原型。
从输出可以看出,person 的原型是一个空对象 {}
。
注意:默认情况下,对象继承自 Object.prototype
。而 Object.prototype
的原型是一个空对象 {}
,这也是 JavaScript 中所有对象的最终原型。
示例 2:getPrototypeOf() 与 setPrototypeOf() 结合使用
// create an empty object
let obj = {};
// create an object named person
let person = {
name: "Vincent",
age: 56,
}
// set person as the prototype of obj
Object.setPrototypeOf(obj, person);
// print the prototype of obj
console.log(Object.getPrototypeOf(obj));
// Output: { name: 'Vincent', age: 56 }
// check if the prototype of obj
// is equal to the person object
console.log(Object.getPrototypeOf(obj) == person)
// Output: true
在上面的示例中,我们首先创建了一个空对象 obj 和一个非空对象 person。
然后,我们使用 setPrototypeOf()
方法将空对象 obj 的原型设置为 person 对象。
当我们使用 getPrototypeOf()
方法打印 obj 的原型时,我们得到的输出是 person 对象。
因此,obj 的原型是 person 对象。
通过使用布尔表达式将 obj 的原型与 person 对象进行比较,可以确认这一点,该表达式返回 true
。
// Boolean expression returns true
Object.getPrototypeOf(obj) == person
示例 3:getPrototypeOf() 用于查找字符串的原型
let str = "JavaScript"
// find the prototype of string
console.log(Object.getPrototypeOf(str));
// Output: [String: ' ']
在上面的示例中,我们调用 Object.getPrototypeOf()
来获取字符串 str 的原型。
输出表明 str 的原型是 String
构造函数。
示例 4:getPrototypeOf() 用于查找函数原型的原型
// define a function that greets
function greet() {
console.log("Hello!")
};
// get the prototype of the above function
console.log(Object.getPrototypeOf(greet));
// Output: [Function]
在上面的示例中,我们创建了一个 greet()
函数,当调用它时会打印 "Hello!"
。
当我们使用 getPrototypeOf()
方法查找 greet()
函数的原型时,输出为 [Function]
。
此输出表明 greet()
的原型是 [Function]
构造函数。
另请阅读