简体   繁体   English

我可以在不使用`this`的情况下在对象的方法中使用对象的属性吗?

[英]can I use an object's property in the object's method without using `this`

In following code, why I cannot access b without this keyword. 在以下代码中,为什么没有this关键字我无法访问b I am using nodejs to run the code 我正在使用nodejs运行代码

var o = {
    a: 0,
    b:0,
    m1: function(){
        return this.a+b; //this doesn't compile
    },
}
console.log(o.m1())

Change this.a + b; 更改this.a + b; to this.a + this.b; this.a + this.b; . There is no variable b but there is a property of the object with that name 没有变量b但是具有该名称的对象的属性

 var o = { a: 1, b: 4, m1: function(){ return this.a + this.b; }, } console.log(o.m1()) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM