在 JavaScript 中,我们可以使用以下方法来获取原型:
-
Object.getPrototypeOf()
:这个方法返回指定对象的原型。它是从 ES5 引入的。 -
function.prototype
:每个 JavaScript 函数实例都有一个prototype
属性。此属性包含可以由实例继承的属性和方法。因此,如果要访问函数的原型,可以使用function.prototype
。
以下是一个示例:
function Animal(name) {
this.name = name;
}
Animal.prototype.sound = function() {
console.log(this.name + ' is making a sound.');
};
var dog = new Animal('Rover');
console.log(Object.getPrototypeOf(dog) === Animal.prototype); // true
console.log(dog.__proto__ === Animal.prototype); // true
console.log(Animal.prototype.isPrototypeOf(dog)); // true
在上面的示例中,我们实例化了一个具有 .name
属性和 sound()
方法的 Animal
对象,并且通过不同的方式获取了它的原型。