在javascript中,访问对象原型属性主要有三种途径:1. 使用非标准的__proto__属性,可直接访问实例的原型,但不推荐在生产环境中使用;2. 使用标准方法object.getprototypeof(),推荐用于安全、规范地获取对象的原型;3. 通过构造函数的prototype属性间接操作原型,适用于定义共享方法和属性。这三种方式共同揭示了javascript原型链的核心机制,理解它们的关系有助于掌握继承、优化性能、避免常见误区,并在实际开发中有效利用原型继承实现代码复用和多态。

在JavaScript中,访问一个对象的原型属性,主要有几种途径:你可以通过非标准的
__proto__
Object.getPrototypeOf()
prototype

谈到JavaScript里对象原型属性的访问,这其实是理解JS面向对象核心的关键一步。我个人觉得,理解它就像是拆开一个盒子,看看里面那些“看不见”的连接是如何工作的。
首先,最直接但也最不推荐在生产代码中直接使用的,是__proto__

function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const alice = new Person('Alice');
console.log(alice.__proto__ === Person.prototype); // true
console.log(alice.__proto__.greet); // [Function: greet]接着,更推荐、更标准的做法是使用Object.getPrototypeOf()
[[Prototype]]
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a sound.`);
};
const dog = new Animal('Buddy');
const protoOfDog = Object.getPrototypeOf(dog);
console.log(protoOfDog === Animal.prototype); // true
protoOfDog.speak(); // 'Buddy makes a sound.' (这里调用的还是实例的speak,因为speak方法在原型上,实例本身没有,会沿着原型链查找)
// 如果你想要访问原型上的特定属性,可以直接通过 protoOfDog.property_name
console.log(Object.getPrototypeOf(dog).speak === Animal.prototype.speak); // true最后,当你谈论“原型属性”时,很多时候你是在指构造函数的prototype
prototype
[[Prototype]]
__proto__
prototype
Constructor.prototype

function Car(model) {
this.model = model;
}
// 通过构造函数的prototype属性添加方法,这是最常见和推荐的方式
Car.prototype.drive = function() {
console.log(`${this.model} is driving.`);
};
const myCar = new Car('Tesla');
myCar.drive(); // Tesla is driving.
// 此时,myCar的__proto__就是Car.prototype
console.log(myCar.__proto__ === Car.prototype); // true理解这三者之间的关系至关重要:实例的
__proto__
Object.getPrototypeOf(instance)
prototype
理解JavaScript的原型链,对我来说,就像是拿到了一张JS对象继承的“地图”。没有这张地图,很多时候你会迷失在各种对象和方法之间,不知道它们是从哪里来的,也不知道它们为什么会表现出那样的行为。这不仅仅是个理论知识,它直接关系到你写出的代码是否高效、是否易于维护。
首先,原型链是JavaScript实现继承的根本机制。不同于Java或C++那种基于类的继承,JS是基于原型的。这意味着当你尝试访问一个对象的某个属性或方法时,如果这个对象本身没有,JS引擎会沿着它的原型链向上查找,直到找到该属性或者到达原型链的顶端(
null
push()
map()
Array.prototype
其次,理解原型链能帮助你编写更高效的代码。共享的方法和属性应该放在原型上,而不是每个实例上都复制一份。比如,如果你有1000个
Person
greet
greet
this.greet = function() {...}greet
greet
Person.prototype
greet
再者,它对this
this
最后,在调试时,如果你知道一个方法可能定义在原型上,或者一个属性可能是从原型继承而来,你就能更快地定位问题。比如,一个对象行为异常,你可能会检查它的原型链上是否有意外的修改,或者某个方法是否被错误地覆盖了。
在实际开发中,关于原型属性的访问,我见过不少“坑”,自己也掉进去过。这些误区往往源于对原型链机制理解不够深入,或者习惯了其他语言的类继承思维。
一个非常常见的误区就是混淆__proto__
prototype
__proto__
prototype
myInstance.prototype.method()
prototype
另一个危险的误区是直接修改或扩展内置对象的Object.prototype
Array.prototype
Array.prototype.myCustomMethod = function() {...}Array.prototype
Array
还有,很多人在遍历对象属性时,不使用hasOwnProperty()
for...in
hasOwnProperty
function Vehicle() {
this.type = 'car';
}
Vehicle.prototype.color = 'red';
const myVehicle = new Vehicle();
for (let key in myVehicle) {
console.log(key + ': ' + myVehicle[key]);
// 输出:
// type: car
// color: red
}
console.log('--- 使用 hasOwnProperty ---');
for (let key in myVehicle) {
if (myVehicle.hasOwnProperty(key)) {
console.log(key + ': ' + myVehicle[key]);
// 输出:
// type: car
}
}不加
hasOwnProperty
color
最后,有时会有人误以为原型链上的方法调用会比实例自身的方法慢很多。虽然理论上存在查找开销,但在现代JS引擎中,这种开销通常微乎其微,几乎可以忽略不计。过度优化而将所有方法都复制到实例上,反而会带来更大的内存开销。性能瓶颈往往出现在更复杂的计算或DOM操作上,而不是原型链的查找。
在日常的JavaScript开发中,原型继承是构建可维护、可扩展代码的基石。我通常会从几个方面去思考如何有效地利用它。
首先,定义共享方法和属性。这是最基本也是最重要的应用。当你有多个对象实例需要共享同一个方法或属性时,将其定义在构造函数的
prototype
User
login()
logout()
User.prototype
User
// 示例:定义共享方法
function User(name, email) {
this.name = name;
this.email = email;
}
User.prototype.login = function() {
console.log(`${this.name} logged in.`);
};
User.prototype.getProfile = function() {
return { name: this.name, email: this.email };
};
const user1 = new User('Alice', 'alice@example.com');
const user2 = new User('Bob', 'bob@example.com');
user1.login(); // Alice logged in.
console.log(user2.getProfile()); // { name: 'Bob', email: 'bob@example.com' }其次,实现继承和多态。通过原型链,我们可以轻松实现对象之间的继承关系。例如,
Student
Person
Object.create()
class
// 示例:实现继承
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}.`);
};
function Student(name, studentId) {
Person.call(this, name); // 调用父类构造函数
this.studentId = studentId;
}
// 核心继承步骤:将Student的原型指向Person原型的一个新对象
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student; // 修正constructor指向
Student.prototype.study = function() {
console.log(`${this.name} (ID: ${this.studentId}) is studying.`);
};
const studentA = new Student('Charlie', 'S001');
studentA.sayHello(); // Hello, my name is Charlie. (继承自Person)
studentA.study(); // Charlie (ID: S001) is studying.这种模式让代码复用性大大提高,并且通过方法重写(多态),你可以让子类拥有父类方法的不同实现。
再者,利用Object.create()
Object.create()
// 示例:使用Object.create()
const baseShape = {
color: 'red',
getArea: function() { return 0; }
};
const circle = Object.create(baseShape);
circle.radius = 5;
circle.getArea = function() {
return Math.PI * this.radius * this.radius;
};
circle.color = 'blue'; // 覆盖原型上的属性
console.log(circle.color); // blue
console.log(circle.getArea()); // 78.539...
console.log(Object.getPrototypeOf(circle) === baseShape); // true最后,虽然ES6的
class
class
super
以上就是js如何访问对象的原型属性的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号