为什么两个变量都没有定义?

时间:2015-12-10 17:06:02

标签: javascript node.js

为什么行console.log(VipUser);console.log(DummyUser);都不会抛出错误?如果在a中运行此代码,为什么不显示“undefined” 浏览器?

(function() {
  var User = function(name, age) {
    this.name = name;
    this.age = age;
  };
  User.prototype.welcome = function() {
    console.log('Welcome ' + this.name);
  };
  User.prototype.getAge = function() {
    return this.age;
  };
  console.log(VipUser);
  console.log(DummyUser);

  function DummyUser(name, surname) {
    this.name = name;
    this.surname = surname;
    this.toString = function() {
      return this.name + ' ' + this.surname;
    }
  }
  DummyUser.prototype.toString2 = function() {
    return this.name + ' ' + this.surname;
  }
  var VipUser = function(name, age, memberId) {

  };
}());

1 个答案:

答案 0 :(得分:2)

您需要移动console.log(),如此:

(function() {
var User = function(name, age){
    this.name = name;
    this.age = age;
};
User.prototype.welcome = function(){
    console.log('Welcome ' + this.name);
};
User.prototype.getAge = function(){
    return this.age;
};

function DummyUser(name, surname) {
    this.name = name;
    this.surname = surname;
    this.toString = function() {
        return this.name + ' ' + this.surname;
    }
}
DummyUser.prototype.toString2 = function() {
    return this.name + ' ' + this.surname;
}
var VipUser = function(name, age, memberId){

};
console.log(VipUser);
console.log(DummyUser);
}());

请参阅此jsfiddle

如果为变量分配匿名函数,则在执行赋值后 之后才能访问它。换句话说,即使匿名函数已被“编译”,它在分配之前也是未定义的。

来自小提琴:

console.log(x);
console.log(hello);

var x = function(t){
        if(t){
      return true;
    }
    return false;
}

function hello(r){
        if(r){
      return true;
    }
    return false;
}

console.log(x);
console.log(hello);

示例代码的前两个日志的输出是:

  

undefined

     

hello(r){ if(r){ return true; } return false; }

然后输出第二个两个日志:

  

(t){ if(t){ return true; } return false; } hello(r){ if(r){ return true; } return false; }