How can I make prototype getTaggedTweet enumerable so no can access this prototype from outside? Can I do it by using the defineProperty method of an object?
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' ? '@' : '#'; }
Making a property enumerable or non-enumerable will not affect whether it's accessible from the outside or not. If it's a property, it will be accessible regardless, with Object.getOwnPropertyNames
, which iterates over non-enumerable properties as well.
const obj = {}; Object.defineProperty(obj, 'amIPrivate', { value: 'no', enumerable: false }); Object.getOwnPropertyNames(obj).forEach((prop) => { console.log(obj[prop]); });
Rather, you can make sure the outside cannot access your method using a closure - make an IIFE which defines the class and the (private, standalone) function inside it, then return the class:
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;
})();
Also note that there's no need to await
things that aren't Promises.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.