如何使构造函数原型枚举



如何使原型getTaggedTweet枚举,以免从外部访问此原型?我可以使用对象的DefineProperty方法吗?

function Tweet_api(tweetID){}
Tweet_api.prototype.getTweetByHandler = async function(){
    const data = await this.getTaggedTweet.call(null, 'handler');
    return data;
};
Tweet_api.prototype.getTweetByHashtag = async function(){
    const data = await this.getTaggedTweet.call(null, 'hashtag');
    return data;
};
Tweet_api.prototype.getTaggedTweet = function(method){
    return method === 'handler' ? '@' : '#';
}

制造属性或不可能量的属性不会影响它是否可以从外部访问。如果是属性,则可以使用Object.getOwnPropertyNames访问,它也可以通过不可设属性进行迭代。

const obj = {};
Object.defineProperty(obj, 'amIPrivate', {
  value: 'no',
  enumerable: false
});
Object.getOwnPropertyNames(obj).forEach((prop) => {
  console.log(obj[prop]);
});

而是,您可以确保外部无法使用A CLOSURE - 制作一个定义类的IIFE,并在其中定义了(私有,独立的)功能,然后返回类:

const Tweet_api = (() => {
  function Tweet_api(tweetID) {}
  Tweet_api.prototype.getTweetByHandler = async function() {
    const data = await getTaggedTweet.call(null, 'handler');
    return data;
  };
  Tweet_api.prototype.getTweetByHashtag = async function() {
    const data = await getTaggedTweet.call(null, 'hashtag');
    return data;
  };
  const getTaggedTweet = method => method === 'handler' ? '@' : '#';
  return Tweet_api;
})();

还请注意,无需await不承诺的事情。

最新更新