Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/454.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 方法错误:未定义方法名称_Javascript_Object_Methods - Fatal编程技术网

Javascript 方法错误:未定义方法名称

Javascript 方法错误:未定义方法名称,javascript,object,methods,Javascript,Object,Methods,为什么这个代码不起作用?我正在尝试使用该方法来添加属性,然后将添加的属性分配给它自己的值 function howLongILivedSomewhere(college, home1, home2) { this.birthHome = 18; this.college = college; this.home1 = home1; this.home2 = home2; this.calcYearsAlive = function() { ret

为什么这个代码不起作用?我正在尝试使用该方法来添加属性,然后将添加的属性分配给它自己的值

function howLongILivedSomewhere(college, home1, home2) {
    this.birthHome = 18;
    this.college = college;
    this.home1 = home1;
    this.home2 = home2;

    this.calcYearsAlive = function() {
    return birthHome + college + home1 +home2;
    };

    this.yearsAlive = calcYearsAlive();
}

var me = new howLongILivedSomewhere(4, 2, 3);

console.log(me);

将构造函数更新为:

function howLongILivedSomewhere(college, home1, home2) {
    this.birthHome = 18;
    this.college = college;
    this.home1 = home1;
    this.home2 = home2;

    this.calcYearsAlive = function() {
      return this.birthHome + this.college + this.home1 + this.home2;
    };

    this.yearsAlive = this.calcYearsAlive();
}

var me = new howLongILivedSomewhere(4, 2, 3);

console.log(me);

当您需要访问对象属性(更多详细信息)时,请使用
this
关键字。

您在方法/属性调用期间错过了
this
关键字。试试下面的方法

  function howLongILivedSomewhere(college, home1, home2) {
    this.birthHome = 18;
    this.college = college;
    this.home1 = home1;
    this.home2 = home2;

    this.calcYearsAlive = function() {
      return this.birthHome + this.college + this.home1 + this.home2;
    };

    this.yearsAlive = this.calcYearsAlive();
}

var me = new howLongILivedSomewhere(4, 2, 3);

console.log(me.yearsAlive); // output: 27
这个关键字是什么? 与其他语言相比,函数的this关键字在JavaScript中的行为稍有不同。严格模式和非严格模式也有一些区别

参考资料:


在方法或方法调用中使用此关键字作为well@Venkatraman非常感谢。检查我的答案,它有解决方案给你!事实上,这仍然不起作用。它给了我一个错误消息:calcYearsAlive没有定义。你说得对。答案更新。太棒了!这次成功了。谢谢你的帮助!