为什么不工作条件?

时间:2015-11-16 07:31:34

标签: javascript angularjs

我有以下部分代码:

var SocketChat = socketFactory({
                ioSocket: (typeof io === 'undefined') ? io.connect('http://test.com:8181') : null
            });

我尝试检查是否存在io对象:

(typeof io === 'undefined')

但我收到错误ReferenceError: io is not defined

3 个答案:

答案 0 :(得分:1)

让我们写出三元声明:

(typeof io === 'undefined') ? io.connect('http://test.com:8181') : null

基本上是:

if(typeof io === 'undefined'){
    io.connect('http://test.com:8181')}
} else {
    null;
}

所以,如果ioundefined,那么您正试图在其上调用.connect

这不起作用。

您可能想要改变您的状况:

io ? io.connect('http://test.com:8181') : null

因此,如果io是真值,则会在其上调用.connect

答案 1 :(得分:1)

使用条件正确的方式,如果io.connect未定义,它如何访问io

  var SocketChat = socketFactory({
                    ioSocket: (typeof io !== 'undefined') ? io.connect('http://test.com:8181') : null
                });

答案 2 :(得分:0)

如果protocol Decoratable{} class A:Decoratable{} class B:Decoratable{} let object:AnyObject = A() object.dynamicType is A.Type//true object.dynamicType is B.Type//false object.dynamicType is Decoratable.Type//true ioundefined应该如何运作?请将您的代码更改为:

io.connect()
相关问题