从localStorage解析ES6类对象不包括类函数

时间:2017-04-26 05:52:21

标签: javascript class local-storage persistence

我想在HTML5 localStorage中保留一个类对象。该类包含我还需要持久化的方法,但解析localStorage对象会发现该对象不同。

class ExcitingMath {

    constructor(firstNumber, secondNumber) {

        this._firstNumber = firstNumber;
        this._secondNumber = secondNumber;
    }

    add() {

        return this._firstNumber + this._secondNumber;
    }

    subtract() {

        return this._firstNumber - this._secondNumber;
    }
}

const eMath = new ExcitingMath(2, 4);

在控制台中记录eMath会显示带有它的属性和方法的类对象:

enter image description here

但是,当localStorage.setItem("math", JSON.stringify(eMath));JSON.parse(localStorage.getItem("math"));来往于localStorage的对象时,它不再包含构造函数或方法。

enter image description here

如何使用localStorage保留原始类实例?

1 个答案:

答案 0 :(得分:3)

这是不可能的,因为JSON.toString只保存对象的STATE,而不是你已经发现的对象的函数。我遇到了同样的“问题”并在我的类中编写了一个函数“fromJSON”,它从localstorage获取JSON并将其转换为对象,如下所示:

class Tweet(dict):
    def __init__(self, tweet_in, encoding  = 'utf-8'):
        super(Tweet, self).__init__(self)
        if tweet_in and 'delete' not in tweet_in:
            self['id']           = tweet_in['id']
            self['geo']          = tweet_in['geo']['coordinates'] if tweet_in['geo'] else None
            self['text']         = tweet_in['text'].encode(encoding)
            self['user_id']      = tweet_in['user']['id'] 
            self['hashtags']     = [x['text'].encode(encoding) for x in tweet_in['entities']['hashtags']]
            self['timestamp']    = dateutil.parser.parse(tweet_in[u'created_at']).replace(tzinfo=None).isoformat()
            self['screen_name']  = tweet_in['user']['screen_name'].encode(encoding)

    def connect_twitter():

        consumer_key    = "personal_info"
        consumer_secret = "personal_info"
        access_token    = "personal_info"
        access_secret   = "personal_info"
        auth            = twitter.OAuth(token           = access_token,
                                        token_secret    = access_secret,
                                        consumer_key    = consumer_key,
                                        consumer_secret = consumer_secret)
        return twitter.TwitterStream(auth=auth)


    def get_next_tweet(twitter_stream, i ):
        block    = False # True
        stream   = twitter_stream.statuses.sample(block=False) 
        tweet_in = None        
        while not tweet_in or 'delete' in tweet_in:
            tweet_in     = stream.next()
            tweet_parsed = Tweet(tweet_in)

        return json.dumps(tweet_parsed)


    def process_rdd_queue(twitter_stream, nb_tweets = 5):`enter code here`
        rddQueue = []
        for i in range(nb_tweets):
             json_twt  = get_next_tweet(twitter_stream, i ) 
             dist_twt  = ssc.sparkContext.parallelize([json_twt], 5)
             rddQueue += [dist_twt]

        lines = ssc.queueStream(rddQueue, oneAtATime=False)
        lines.pprint()

enter code here

try    : sc.stop()
except : pass

sc  = SparkContext(appName="PythonStreamingQueueStream")
ssc = StreamingContext(sc, 1)

twitter_stream = connect_twitter()
process_rdd_queue(twitter_stream)

try    : ssc.stop(stopSparkContext=True, stopGraceFully=True)
except : pass

ssc.start()
time.sleep(2)
ssc.stop(stopSparkContext=True, stopGraceFully=True)

然后您可以按如下方式使用它:

class ExcitingMath {

    constructor(firstNumber, secondNumber) {

        this._firstNumber = firstNumber;
        this._secondNumber = secondNumber;
    }

    add() {

        return this._firstNumber + this._secondNumber;
    }

    subtract() {

        return this._firstNumber - this._secondNumber;
    }

    static fromJSON(serializedJson) {
        return Object.assign(new ExcitingMath(), JSON.parse(serializedJson))
    }
}