如何制作没有引号(不是字符串)的JavaScript对象值?

时间:2017-03-13 23:14:00

标签: javascript angularjs videogular

Videogular Angular视频播放器喜欢在这样的对象中引用视频:

{
    preload: "auto",
    sources: [
        {
            src: $sce.trustAsResourceUrl("http://static.videogular.com/assets/videos/videogular.mp4"),
            type: "video/mp4"
        }
    ],
    theme: "bower_components/videogular-themes-default/videogular.css"
}

$sce.trustAsResourceUrl通过ng-sanitize运行网址以防止恶意代码。

在我的控制器中,我将视频上传到Firebase存储后制作此对象,Firebase存储会返回snapshot个对象:

var videoObject = {
    preload: "auto",
    sources: [
        {
            src: "$sce.trustAsResourceUrl(" + $scope.snapshot.downloadURL + ")",
            type: "video/" + $scope.mediaFormat
        },
    ],
    theme: {
        url: "http://www.videogular.com/styles/themes/default/latest/videogular.css"
    }
};

结果是:

{
    preload: "auto",
    sources: [
        {
            src: "$sce.trustAsResourceUrl(http://static.videogular.com/assets/videos/videogular.mp4)",
            type: "video/mp4"
        }
    ],
    theme: "bower_components/videogular-themes-default/videogular.css"
}

当我希望src不是字符串时,$sce.trustAsResourceUrl键的值是字符串,这不起作用。

如果我以这种方式制作对象:

var videoObject = {
    preload: "auto",
    sources: [
        {src: $sce.trustAsResourceUrl +'("' + $scope.snapshot.downloadURL + '")', type: "video/" + $scope.mediaFormat}
    ],
    theme: {
        url: "http://www.videogular.com/styles/themes/default/latest/videogular.css"
    }
};

然后我得到:

{
    preload: "auto",
    sources: [
        {
            src: "function (b){return g(a,b)}(\"http://static.videogular.com/assets/videos/videogular.mp4)",
            type: "video/mp4"
        }
    ],
    theme: "bower_components/videogular-themes-default/videogular.css"
}

根据Mozilla," JavaScript对象是键和值之间的映射。键是字符串(或符号),值可以是任何值。"如果值可以是任何值,那么如何创建部分为字符串且部分不是字符串的值?什么是"部分是字符串,部分不是字符串"叫什么名字?文字?

2 个答案:

答案 0 :(得分:0)

我觉得这样的事情应该有效,

function something() { return $sce.......; } source[0].src = something();

答案 1 :(得分:0)

让我们专注于给您带来麻烦的片段:

{
    src: "$sce.trustAsResourceUrl(" + $scope.snapshot.downloadURL + ")",
    type: "video/" + $scope.mediaFormat
},

您正在执行字符串连接

"$sce.trustAsResourceUrl(" + // type: String
$scope.snapshot.downloadURL +  // type: String
")"                            // type: String
// Result is of type: String

类似地,在第二个示例中,您尝试将函数与字符串连接,这将导致函数被强制转换为字符串。如果您想要一个明确的此行为示例,请运行以下代码段:

function hello () { return "hello" }
var result = hello + "world"
// ----------------^ this implicitly calls toString on the function
console.log("result: ", hello + "world")
console.log("result type: ", typeof result)

解决方案:调用函数,将url作为参数传递:

{
    src: $sce.trustAsResourceUrl($scope.snapshot.downloadURL),
    type: "video/" + $scope.mediaFormat
},