获取类中的值

问题描述 投票:0回答:1

我有一个这样的构造:

myObject = new constructObject( "myName" ), {
    strVar: "myStrVar",
    myFunction: function() {
        // here is my problem
        // I would like to have an access to strVar

        ?how can I get here the value of strVar

   }
});

非常感谢

我在互联网上查找并尝试了很多代码片段

javascript-objects
1个回答
0
投票

您似乎想访问 myObject 对象的 myFunction 方法中的 strVar 属性。为了实现这一点,您可以使用 JavaScript 中的闭包概念。以下是修改代码以使其正常工作的方法:

function constructObject(name) {
    // Create an object with strVar property
    var obj = {
        strVar: "myStrVar",
        myFunction: function() {
            // You can access strVar directly here
            console.log(this.strVar);
        }
    };
    
    // Assign the 'name' argument to the 'name' property of the object
    obj.name = name;
    
    // Return the object
    return obj;
}

// Create an instance of constructObject
var myObject = new constructObject("myName");

// Call myFunction to access strVar
myObject.myFunction(); // This will log "myStrVar" to the console

在此代码中:

constructObject 是一个构造函数,它使用 strVar 属性和 myFunction 方法创建对象。 在 myFunction 内部,您可以使用 this.strVar 直接访问 strVar 属性。 当您使用 new constructObject("myName") 创建 constructObject 实例时,它会返回一个具有 strVar 属性和 myFunction 方法的对象。然后,您可以在此对象上调用 myFunction 来访问 strVar 属性。

© www.soinside.com 2019 - 2024. All rights reserved.