JS Proxy setPrototypeOf()

🌙
手机阅读
本文目录结构

handler.setPrototypeOf() 方法主要用来拦截 Object.setPrototypeOf().

语法

var p = new Proxy(target, {
  setPrototypeOf: function(target, prototype) {
  }
});

参数

以下参数传递给 setPrototypeOf 方法. 

target

被拦截目标对象.

prototype

对象新原型或为null.

返回值

如果成功修改了[[Prototype]]setPrototypeOf 方法返回 true,否则返回 false.

描述

这个 handler.setPrototypeOf 方法用于拦截 Object.setPrototypeOf().

拦截

这个方法可以拦截以下操作:

Invariants

如果违反了下列规则,则proxy将抛出一个TypeError:

  • 如果 target 不可扩展, 原型参数必须与Object.getPrototypeOf(target) 的值相同.

示例

如果你不想为你的对象设置一个新的原型,你的handler’s的setPrototypeOf方法可以返回false,也可以抛出异常。

The former approach means that any operation that performs such mutation, that throws an exception on failure to mutate, will have to create the exception itself.  For example, Object.setPrototypeOf() will create and throw a TypeError itself.  If the mutation is performed by an operation that doesn’t ordinarily throw in case of failure, such as Reflect.setPrototypeOf(), no exception will be thrown.

var handlerReturnsFalse = {
    setPrototypeOf(target, newProto) {
        return false;
    }
};

var newProto = {}, target = {};

var p1 = new Proxy(target, handlerReturnsFalse);
Object.setPrototypeOf(p1, newProto); // throws a TypeError
Reflect.setPrototypeOf(p1, newProto); // returns false

The latter approach will cause any operation that attempts to mutate, to throw.  This approach is required if you want even non-throwing operations to throw on failure, or you want to throw a custom exception value.

var handlerThrows = {
    setPrototypeOf(target, newProto) {
        throw new Error('custom error');
    }
}; 

var newProto = {}, target = {};

var p2 = new Proxy(target, handlerThrows);
Object.setPrototypeOf(p2, newProto); // throws new Error("custom error")
Reflect.setPrototypeOf(p2, newProto); // throws new Error("custom error")

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)[[SetPrototypeOf]] Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)[[SetPrototypeOf]] Draft  

See also

AXIHE / 精选资源

浏览全部教程

面试题

学习网站

前端培训
自己甄别

前端书籍

关于朱安邦

我叫 朱安邦,阿西河的站长,在杭州。

以前是一名平面设计师,后来开始接接触前端开发,主要研究前端技术中的JS方向。

业余时间我喜欢分享和交流自己的技术,欢迎大家关注我的 Bilibili

关注我: Github / 知乎

于2021年离开前端领域,目前重心放在研究区块链上面了

我叫朱安邦,阿西河的站长

目前在杭州从事区块链周边的开发工作,机械专业,以前从事平面设计工作。

2014年底脱产在老家自学6个月的前端技术,自学期间几乎从未出过家门,最终找到了满意的前端工作。更多>

于2021年离开前端领域,目前从事区块链方面工作了