填充对象的javascript对象文字方法

时间:2017-06-21 13:20:32

标签: javascript

我有一个像这样的对象:

var data = {
    scope: "some_scope",
    redirect_urls: {
        return_url: return_url,
        cancel_url: cancel_url
    },
    someotherobj:{
        method: "get"
    },
    setRedirectUrls: function(return_url, cancel_url) {
        this.redirect_urls.return_url = return_url;
        this.redirect_urls.cancel_url = cancel_url;
    }
}

我希望有这个对象JSON.strigify'但是我想念一些东西或者我不知道这是不是正确的方式:

data.setRedirectUrls('http://www...','http://www....');
var json = JSON.stringify(data);

但我得到ReferenceError: "return_url" is not defined.

2 个答案:

答案 0 :(得分:3)

问题是你是否尝试使用尚未定义/不存在的变量来实例化对象属性,将它们更改为空字符串。



var data = {
  scope: "some_scope",
  redirect_urls: {
    return_url: "",
    cancel_url: ""
  },
  someotherobj: {
    method: "get"
  },
  setRedirectUrls: function(return_url, cancel_url) {
    this.redirect_urls.return_url = return_url;
    this.redirect_urls.cancel_url = cancel_url;
  }
}

data.setRedirectUrls('http://www...', 'http://www....');
var json = JSON.stringify(data);

console.log(json)

.as-console-wrapper {max-height: 100% !important;top: 0;}




答案 1 :(得分:2)

嘿看看我的片段,我在那里给我的答案添加了一个解释。



var data = {
    scope: "some_scope",
    redirect_urls: {
        return_url: '', //          return_url: return_url; Can't do this here because they don't exist.
        cancel_url: ''  //          cancel_url: cancel_url;
    },
    someotherobj:{
        method: "get"
    }
}

// After you know the structure of your object then add the actions to it here.

data.setRedirectUrls = function(return_url, cancel_url) {
    this.redirect_urls.return_url = return_url;
    this.redirect_urls.cancel_url = cancel_url;
}

data.setRedirectUrls('http://www...','http://www....');
var json = JSON.stringify(data);

console.log(json);