省略了对象的构造函数属性

时间:2014-07-17 18:37:08

标签: javascript jquery

我定义了一个简单的JavaScript类

function Demo(a,b){
         this.a=a;
         this.b=b;
}

//and Demo objects inherit from the prototype
Demo.prototype = {
     toString : function() { return this.a + " " + this.b ; }
}

//usage
var d = new Demo("Hello","world");
console.log(d);

但实例没有构造函数属性。这是为什么?我的意思是当我这样做时

console.log(d.constructor) //function Object() { [native code] } 

4 个答案:

答案 0 :(得分:1)

对象文字(花括号)继承自Object,因此构造函数属性将与Object相同,除非您使用自己的值覆盖它,就像在zzzzBov的答案中一样。如果您在Demo.prototype = new Object();中直接从Object继承,则会得到相同的结果。

从继承自Function的对象继承,为您提供了您正在寻找的构造函数属性,而无需自己定义它。试试这个:

function DemoBase(a,b){
         this.toString=function() { return this.a + " " + this.b ; }
}

function Demo(a,b){
         this.a=a;
         this.b=b;
}
Demo.prototype = new DemoBase();

//usage
var d = new Demo("Hello","world");
console.log(d);
console.log(d.constructor) 

答案 1 :(得分:0)

 function Demo(a,b){
     this.a = a;
     this.b = b;
     this.getA = function() { return this.a };
     this.getB = function() { return this.b };
     this.concat = function() {return this.a + ' ' + this.b};
 }

  Demo.prototype.toString = function() { return this.a + ' ' + this.b ; }

  //usage
  var d = new Demo('Hello','world');
  console.log(d.concat());
  console.log(d.toString());

以下是您想要的screenshot

答案 2 :(得分:0)

可能你正在寻找这个。

function Demo(a,b){
     this.a=a;
     this.b=b;
}

Demo.prototype.toString = function toString() { return this.a + " " + this.b ; }

var d = new Demo('Hello','world');
console.log(d);

我在这里创造了一个小提琴 http://jsfiddle.net/moyeen52/NEv4M/1/

答案 3 :(得分:0)

如果您希望构造函数属性指向Demo,则需要指定它:

function Demo(a, b) {
    this.a = a;
    this.b = b;
}

Demo.prototype = {
     constructor: Demo,
     toString: function () {
         return this.a + ' ' + this.b;
     }
};

var d = new Demo('Hello', 'world');
console.log(d.constructor);

这将打印以下内容:

function Demo(a, b) {
    this.a = a;
    this.b = b;
}

如果您希望将d视为字符串,则需要强制转换它:

console.log('' + d); //prints 'Hello world';
相关问题