最准确的判断方式是在构造函数内部使用 new.target,若函数通过 new 调用则 new.target 指向构造函数,否则为 undefined;2. 对于已创建的对象,可使用 instanceof 判断其原型链是否包含构造函数的 prototype,但该方法在跨 realm 或原型链被修改时会失效;3. 可通过 object.getprototypeof() 或 isprototypeof() 更精确地检查原型链关系;4. constructor 属性不可靠,因其可被修改;5. 可在构造函数中添加自定义标记(如 this._isnewinstance = true)来实现可靠的“事后”判断,前提是能控制构造逻辑。最终,最推荐的方案是在构造时用 new.target 控制行为,外部判断则结合 instanceof 与原型检查并注意其局限性。

在JavaScript里,要百分之百地“事后”判断一个对象是不是通过
new
new.target
instanceof

判断一个对象是否通过
new
new.target
new
new
new.target
undefined
new
举个例子,假设我们有一个
Person

function Person(name) {
// 在这里判断 new.target
if (!new.target) {
// 如果没有使用 new 调用,则返回一个通过 new 创建的实例
console.warn("建议使用 new 关键字创建 Person 实例。");
return new Person(name);
}
this.name = name;
console.log(`Person 实例 ${this.name} 已创建。`);
}
const person1 = new Person('Alice'); // 正常创建
const person2 = Person('Bob'); // 尝试不使用 new 创建,会被内部修正
console.log(person1 instanceof Person); // true
console.log(person2 instanceof Person); // true这种模式,在我日常写一些库或者框架的时候,用得特别多,它能有效避免用户误操作导致的问题。
如果对象已经创建,且我们无法修改其构造函数,那么
instanceof
prototype

function Animal(type) {
this.type = type;
}
const dog = new Animal('Dog');
const cat = new Animal('Cat');
console.log(dog instanceof Animal); // true
console.log(cat instanceof Animal); // true
const obj = {};
console.log(obj instanceof Animal); // false但
instanceof
new.target
new.target
new
new
new.target
new
new
new.target
undefined
这有什么用呢?在我看来,它最大的价值在于“防御性编程”和“弹性构造”。
防御性编程:强制使用 new
就像前面
Person
!new.target
new
new
this
function Product(name, price) {
if (!new.target) {
// 没用 new?那我帮你 new 一个
console.warn("Product 构造函数必须通过 new 关键字调用!");
return new Product(name, price);
}
this.name = name;
this.price = price;
}
const p1 = new Product('Laptop', 1200); // 正常
const p2 = Product('Mouse', 25); // 会被自动修正并警告
console.log(p1.name, p2.name);这种做法,让你的API接口变得更加健壮,减少了用户的犯错空间。
弹性构造:根据调用方式调整行为
除了强制,
new.target
new
function Greeter(greeting) {
if (new.target) {
// 如果是 new 调用,初始化实例
this.greeting = greeting;
console.log("Greeter 实例被构造");
} else {
// 如果是普通调用,返回一个默认的 Greeter 实例
console.log("返回一个默认 Greeter 实例");
return new Greeter("Hello, default!");
}
}
const myGreeter = new Greeter("Hi there!");
console.log(myGreeter.greeting); // "Hi there!"
const defaultGreeter = Greeter();
console.log(defaultGreeter.greeting); // "Hello, default!"这让你的函数能够适应不同的使用场景,提供更友好的API。当然,这种灵活性也可能增加一点点理解成本,所以在使用时需要权衡。
instanceof
instanceof
[[Prototype]]
prototype
一个很常见的场景就是跨 Realm (跨域/iframe) 对象。每个 JavaScript Realm(比如一个浏览器窗口、一个 iframe 或者 Node.js 的 vm 模块创建的上下文)都有自己独立的全局对象和内置构造函数。这意味着,一个在 iframe A 中创建的对象,即使它是
Array
instanceof Array
false
Array
prototype
<!-- index.html -->
<iframe id="myFrame" src="about:blank"></iframe>
<script>
const iframe = document.getElementById('myFrame');
const iframeDoc = iframe.contentWindow.document;
iframeDoc.write('<script>parent.myArrayInIframe = [];</script>');
iframeDoc.close();
setTimeout(() => {
const arrInParent = [];
const arrInIframe = window.myArrayInIframe;
console.log(arrInParent instanceof Array); // true (在当前 Realm)
console.log(arrInIframe instanceof Array); // false (来自不同 Realm 的 Array 构造函数)
}, 100);
</script>你看,即使它们看起来都是数组,
instanceof
另一个是原型链被修改的情况。虽然不常见,但如果有人手动修改了对象的原型链,
instanceof
function CustomObject() {}
const obj = new CustomObject();
// 正常情况
console.log(obj instanceof CustomObject); // true
// 修改原型链
Object.setPrototypeOf(obj, Object.prototype);
console.log(obj instanceof CustomObject); // false (原型链被截断,CustomObject.prototype 不再在其中)最后,如果你的目标是判断一个对象是不是“某个类型”的实例,而不是特指“通过
new
instanceof
Symbol.iterator
Array
Map
new.target
instanceof
当我们无法使用
new.target
instanceof
1. 使用 Object.getPrototypeOf()
Object.getPrototypeOf()
[[Prototype]]
Object.prototype.isPrototypeOf()
function MyConstructor() {}
const myInstance = new MyConstructor();
// 检查 myInstance 的原型链上是否存在 MyConstructor.prototype
console.log(MyConstructor.prototype.isPrototypeOf(myInstance)); // true
// 也可以这样组合判断,虽然和 instanceof 效果类似,但理解起来更直接
console.log(Object.getPrototypeOf(myInstance) === MyConstructor.prototype); // true
// 注意:这只检查直接原型,如果中间有继承,则不为 true
// 而 isPrototypeOf 会检查整个原型链isPrototypeOf
instanceof
constructor
Symbol.hasInstance
2. 检查 constructor
每个对象通常都有一个
constructor
function AnotherConstructor() {}
const anotherInstance = new AnotherConstructor();
console.log(anotherInstance.constructor === AnotherConstructor); // true
console.log(anotherInstance.constructor.name); // "AnotherConstructor"然而,这个方法非常不推荐作为判断对象是否通过
new
constructor
function Parent() {}
function Child() {}
Child.prototype = new Parent(); // 继承 Parent 的原型,但 constructor 没改
Child.prototype.constructor = Child; // 修正 constructor
const childInstance = new Child();
console.log(childInstance.constructor === Child); // true
console.log(childInstance.constructor === Parent); // false
console.log(childInstance instanceof Child); // true
console.log(childInstance instanceof Parent); // true
// 如果 constructor 没修正,或者被恶意修改
function BadConstructor() {}
const badInstance = new BadConstructor();
badInstance.constructor = String; // 随便改
console.log(badInstance.constructor === BadConstructor); // false
console.log(badInstance instanceof BadConstructor); // true所以,
constructor
3. 添加自定义标记或属性
在某些特定场景下,如果你的设计允许,你可以在构造函数内部给实例添加一个私有(或伪私有)的标记,来明确它是否是通过
new
function TaggedObject() {
if (!new.target) {
return new TaggedObject();
}
this._isNewInstance = true; // 添加一个标记
// ... 其他初始化
}
const tagInstance = new TaggedObject();
const nonTagInstance = TaggedObject(); // 也会被 new
console.log(tagInstance._isNewInstance); // true
console.log(nonTagInstance._isNewInstance); // true这种方法完全依赖于你自己的约定和实现,但它在你知道所有可能的创建路径时,可以提供最直接、最可靠的“事后”判断依据。这就像在产品出厂时贴一个“合格证”,简单直接。
总的来说,判断一个对象是否通过
new
new.target
instanceof
Object.getPrototypeOf()
以上就是js怎么判断对象是否通过new创建的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号