首页 > js面向对象读取值问题

js面向对象读取值问题

如何读取到"t1"中的值(i am a tester)

function Test() {
        this.defaults = {
            "t1": "i am a tester"
            "t2": 这里如何读取到 "t1"中的值(i am a tester)
        };
 }

    var test = new Test();

1.

function Test() {
    this.defaults = {
        "t1": "i am a tester",
        "copyT1": function(){
            console.log(this.t1);
        }
    };
    
    this.defaults.copyT1();
 }

var test = new Test();
test.defaults.t1="new t1 value";
test.defaults.copyT1();

2.

function Test() {
    var t1Value="i am a tester";
    this.defaults = {
        "t1": t1Value,
        "copyT1":  '这里如何读取到 "t1"中的值'+ t1Value
    };
 }
var test = new Test();
console.log(test.defaults.copyT1);

构造函数中的this指的是实例,也就是test

如果你要在copyT1中获取t1,使用this.defaults.t1

如果你要获取特定实例(test)的t1,使用test.defaults.t1



function Test() {
        this.defaults = {
            "t1": "i am a tester",
            "copyT1": '这里如何读取到 "t1"中的值(i am a tester)'
        };
 }
(new Test()).defaults["t1"]
"i am a tester"

// or

Test.call(window) || console.log(defaults.t1)

function Test() {
  this.defaults = {
        "t1": "i am a tester",
        "copyT1": function(){
            console.log(this.t1);
        }
    };
 }

var test = new Test();
test.defaults.copyT1();

你是想要这样么?  不是很懂前面的前辈说的this.defaults.t1。

function Test() {
        this.defaults = {
            "t1": "i am a tester"
            /*
                这里使用(this.t1)肯定是undefined,因为this代表的应该是Test;
                this.defaults.t1,也是拿不到的,this.defaults还在定于中。。。怎么可能拿到呢?
                不知道为什么用这样的需求,既然是t1的复制品,用t1不好了。。。
            */
            "copyT1": 这里如何读取到 "t1"中的值(i am a tester)  
        };
 }

 var test = new Test();

【热门文章】
【热门文章】