构造函数的返回不同于“ [Object object]”。 [英] Constructor function return is other than "[Object object]"

查看:69
本文介绍了构造函数的返回不同于“ [Object object]”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用String构造函数时,我总是想知道它是如何制成的。即使使用 new运算符实例化它,它也会返回您指定为参数的字符串:

When I use the String constructor I allways wonder how is it made.It returns the string you specificed as a parameter even though it is instanciated with the "new" operator like :

  var str = new String("Hello World")
  //str == "Hello World"

如果我创建一个构造函数并给它一个返回值,当实例化时它会返回一个对象:

If I make a constructor and I give it a return value it returns an Object when instanciated :

  function CreateString(st) {
  return ''+st 
  }
  var MyString = new CreateString("Hello there!")
  //MyString == "[Object object]"

如何创建返回值的构造函数Other比[Object object]吗?

How can I create a constructor that returns a value Other than [Object object] ?

更新:
我正在尝试创建一个既具有属性又具有值的构造函数,如:

Update: I am trying to create a constructor function that has both properties and a value itself like :

   function MyConstructor() {
    this.myMethod = function() {
     return 73
    }
     return 25
   }
    /*I want MyConstructor to have the value 25 and the myMethod method */
   alert(MyConstructor()) // to be 25
   alert(MyConstructor().myMethod()) //to be 73


推荐答案

您可以替换 toString()所需类中的函数定义。

You can replace toString() function definition in the desired class.

function CreateString() {
  function toString() { return 'foo' }
}

示例: Number.prototype.toString()

这篇关于构造函数的返回不同于“ [Object object]”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆