Handlebars.js: 对原型属性的访问控制

创建于 2020-01-11  ·  3评论  ·  资料来源: handlebars-lang/handlebars.js

在 #1633 和 #1634 的评论和引用的问题之后,我认为创建一个允许将给定类的原型列入白名单的运行时选项是一个好主意。

调用模板机智

template ({some: "input object"}, { allowedPrototypes: [
  Test
] })

如果以下情况为真,将允许解析属性。

parent[propertyName] === Test.prototype[propertyName] && Test.prototype.hasOwnProperty(propertyName)

我认为在 Web 服务器中使用自定义类时会很有帮助,因为在这样的环境中关闭原型检查肯定不会省事。

我想对此发表意见。

feature

最有用的评论

一个潜在的问题是,在这种情况下,用户会期望将B添加到允许的原型中会起作用:

class A { get a() { return 'a' } }
class B extends A {}

const parent = new B();
parent['a'] === B.prototype['a'] && B.prototype.hasOwnProperty('a') // => false

这还不错,它只需要记录在案,但可能会让很多人感到惊讶。

所有3条评论

一个潜在的问题是,在这种情况下,用户会期望将B添加到允许的原型中会起作用:

class A { get a() { return 'a' } }
class B extends A {}

const parent = new B();
parent['a'] === B.prototype['a'] && B.prototype.hasOwnProperty('a') // => false

这还不错,它只需要记录在案,但可能会让很多人感到惊讶。

我们还可以检查超类是否被列入白名单,因此您只需将“A”列入白名单,以便从“A”和“B”中获取属性。

反之则更加困难,因为它需要将所有原生类列入黑名单,而这可能会随着时间而改变。

@nknapp是否可以使用getPrototypeOfgetOwnPropertyDescriptor来查看 getter 是否已定义。 我不确定这是否会回归到已经解决的问题。

class Example {
  get hello() {
    return 'world';
  }
}

const obj = new Example();
console.log(obj.hello);
// "world"
console.log(Object.getOwnPropertyDescriptor(obj, 'hello'));
// undefined
console.log(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), 'hello'));
// { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined }

来源: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#get_Vs._defineProperty

此页面是否有帮助?
0 / 5 - 0 等级