【问题标题】:why object properties are coming as undefined when i already set them为什么当我已经设置对象属性时它们是未定义的
【发布时间】:2013-01-18 23:57:25
【问题描述】:
function detail(){
  this.html = this.name;
}

var detail1 = new detail();
detail1.name = 'xyz';
console.log(detail1.html);

上面的代码给出了undefined 作为输出。但我已经将名称设置为“xyz”;我是面向对象的 JavaScript 的新手。请帮忙。

【问题讨论】:

    标签: javascript oop object prototype


    【解决方案1】:

    这是因为当您通过复制 html 属性来初始化它时,nameundefined

    解决方案是在构造函数中传递它:

    function detail(name){
      this.name = name;
      this.html = this.name;
    }
    
    var detail1 = new detail();
    console.log(detail1.html);
    

    另一个解决方案是让 html 成为一个函数:

    function detail(){
    }
    detail.prototype.html = function(){
       return this.name;
    }
    var detail1 = new detail();
    detail1.name = 'xyz';
    console.log(detail1.html()); // <- notice the parenthesis here : html is a function
    

    第三个方法是在您更改name 时更改html

    function detail(){
    }
    detail.prototype.setName = function(name){
       this.html = name;
    }
    var detail1 = new detail();
    'xyz';
    detail1.setName('xyz');
    console.log(detail1.html);
    

    【讨论】:

    • 所以所有的对象属性都应该作为函数的参数给出?
    • @user1411662 不一定:还有其他解决方案(见编辑)。你必须选择最适合你的。
    【解决方案2】:

    将名称作为参数传递给函数。当前,当创建详细对象的新实例时,其名称属性未定义。它是在调用构造函数之后设置的,为时已晚。

    function detail(name){
      this.html = "<li><a href='#'>"+name+"</a><a>"+"<li>";
    }
    
    var detail1 = new detail('xyz');
    console.log(detail1.html);
    

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 1970-01-01
      • 2015-12-12
      • 2013-02-07
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多