Javascript-初始化变量?

Javascript-初始化变量?,javascript,constructor,Javascript,Constructor,在小提琴中,我在调用show方法时没有定义。怎么了 我在寻找什么-在调用对象时尝试初始化名称和年龄 function a(name, age) { this.name; this.age; (function x() { this.name = name; this.age = age alert(this.name+" <<inside self invoking>> "+this.age); })(); this.show = func

在小提琴中,我在调用show方法时没有定义。怎么了

我在寻找什么-在调用对象时尝试初始化名称和年龄

function a(name, age) {
this.name;
this.age;    
(function x() {
    this.name = name;
    this.age = age
    alert(this.name+" <<inside self invoking>> "+this.age);
})();
this.show = function() { alert(this.name+" <<show>> "+this.age); }
}

var a1 = new a("rahul", 24);
a1.show();
功能a(姓名、年龄){
这个名字;
这个年龄;
(职能x(){
this.name=名称;
这个年龄
警报(this.name+“”+this.age);
})();
this.show=function(){alert(this.name+“”+this.age);}
}
var a1=新a(“rahul”,24);
a1.show();

正确构建

function a(name, age) {
  this.age  = age;
  this.name = name;
  show: function() { alert(name+' '+age); }
}
去掉
x()
函数。它是不需要的,并且会导致问题,因为Javascript中每次调用函数时都会重置
this
,因此
x()
函数中
this
的值要么是
窗口
对象,要么是
未定义的
(如果处于严格模式)

您可以改为使用此简化:

function a(name, age) {
    this.name = name;
    this.age = age;    
    this.show = function() { alert(this.name+" <<show>> "+this.age); }
}

var a1 = new a("rahul", 24);
a1.show();
功能a(姓名、年龄){
this.name=名称;
这个。年龄=年龄;
this.show=function(){alert(this.name+“”+this.age);}
}
var a1=新a(“rahul”,24);
a1.show();

您在内部函数x中创建了一个新的作用域,因此“this”与前面的“this”不同。也许你想要定义的是

function a(name, age) {
  this.name;
  this.age; 
  var that = this;
    (function x() {
        that.name = name;
        that.age = age
        alert(that.name+" <<inside self invoking>> "+that.age);
    })();
    this.show = function() { alert(this.name+" <<show>> "+this.age); }
}

var a1 = new a("rahul", 24);
a1.show();
功能a(姓名、年龄){
这个名字;
这个年龄;
var=这个;
(职能x(){
that.name=name;
年龄
警告(that.name+“”+that.age);
})();
this.show=function(){alert(this.name+“”+this.age);}
}
var a1=新a(“rahul”,24);
a1.show();

我想您正在寻找它。

您还没有在函数a()中初始化this.name和this.age……通过闭包概念,函数的值不应该是name@jfriend00我从来没有说过这是一开始的答案。@Rafael-你把它作为一个答案贴了出来。这不是答案,也解决不了任何问题。@jfriend00当然,这解释了为什么他不能在没有这些参数的函数中使用它。@Rafael-但是
x
内部
this
的问题与
x
缺少参数无关。
x()
函数的意义何在。这一点都不需要。嗯,这一点也不需要,但如果我认为他正在寻找一个示例来向他展示javascript中的作用域的话。一些说明性的东西来了解范围是如何定义的work@ReikVal说得好..肯定不需要x()函数。。。jfriend00..你最好向问这个问题的用户和他的要求澄清一下…每个人的回答都不好请检查小提琴-为什么它会提示“结果”?有什么想法吗?看起来有点像个傻瓜。结果窗口的名称可能为result。