Object.create继承时,子对象调用父原型上的方法,this自动指向子对象;方法必须定义在Parent.prototype上,而非实例属性,且需通过child.method()形式调用。

在使用 Object.create 实现继承时,子对象调用从父对象“借来”的方法,this 默认指向**调用该方法的对象(即子对象)**,而不是父对象——这是 JavaScript 原型链的自然行为,无需额外绑定。关键在于:方法必须定义在父对象的原型(或其 prototype 链上),且通过子对象正常调用(如 child.method()),this 就会自动绑定到 child。
方法必须放在原型链上,不能是父实例属性
如果父对象的方法是作为**实例属性**(比如在构造函数里用 this.fn = function(){...})定义的,那么它不会被 Object.create(Parent.prototype) 继承,子对象根本访问不到;即使手动复制过去,也容易丢失 this 绑定上下文。
✅ 正确做法:把共享方法放在父构造函数的 prototype 上:
function Parent() {}
Parent.prototype.sayName = function() {
console.log(this.name); // this 指向调用者(子对象)
};
<p>function Child(name) {
this.name = name;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;</p><p>const child = new Child('Alice');
child.sayName(); // 'Alice' —— this 指向 child
避免直接赋值父方法到子对象属性
如果写成 child.sayName = Parent.prototype.sayName,再调用 child.sayName(),this 依然正确指向 child;但若写成 const fn = Parent.prototype.sayName; fn();,此时 this 会变成 undefined(严格模式)或全局对象(非严格),因为脱离了调用对象。
立即学习“Java免费学习笔记(深入)”;
所以确保调用形式是 obj.method(),而不是先解构再调用。
需要显式绑定的场景(少数情况)
只有当方法被当作回调、传入高阶函数、或需固定执行上下文时,才需手动绑定:
- 使用 .bind(child) 返回新函数
- 使用箭头函数包装:() => child.sayName()
- 在事件监听等异步场景中,常用 handleClick = () => this.sayName()(类字段语法)
但这些属于通用 this 控制技巧,和 Object.create 继承本身无关。
检查原型链是否连通
若 this 意外指向了父对象或 undefined,大概率是原型没设对:
- 忘了设置
Child.prototype.constructor = Child(不影响this,但影响可靠性) - 错误地写成
Child.prototype = Object.create(Parent)(应是Parent.prototype) - 父方法定义在
Parent函数自身上(如Parent.sayName = ...),而非其prototype
可用 child.__proto__ === Parent.prototype 或 child instanceof Parent 验证继承关系。


















