Javascript 用户定义对象的原型做什么?

Javascript 用户定义对象的原型做什么?,javascript,Javascript,我不明白您为什么需要UserException.prototype。每个UserException对象都会以这种方式自动共享toString函数。您可以在构造函数中分配该函数: // Create an object type UserException function UserException (message){ this.message=message; this.name="UserException"; } // Make the exception

我不明白您为什么需要UserException.prototype。

每个UserException对象都会以这种方式自动共享toString函数。您可以在构造函数中分配该函数:

// Create an object type UserException  
function UserException (message){  
  this.message=message;  
  this.name="UserException";  
}  

// Make the exception convert to a pretty string when used as  
// a string (e.g. by the error console)  
UserException.prototype.toString = function (){  
  return this.name + ': "' + this.message + '"';  
}  
但是现在,每个实例化还将为toString实例化一个新的不同函数对象。

原型应用于通过新操作符创建的对象,如下所示:

function UserException(message) {
  // whatever
  this.toString = function() { /* ... */ };
}
因此,现在可以在user_exception对象上访问原型中存储的所有属性和方法:

在以下声明中:

alert(user_exception); //alerts UserException: Error
1它构造了一个新的UserException对象,传入的值太高了!串


2该新对象被交给throw,它需要一个具有定义在其上的.toString方法的对象,然后该对象将输出到控制台的错误日志。

这取决于是否将UserException用作单例

当您使用.prototype时,var foo=new UserException的每个实例都有自己的this.toString副本,其作用域将是该对象


您通常不会在构造函数中分配函数,因为每个实例都会在内存中获得为其创建的函数的副本。根据实际对象定义对其进行原型化,使其保持在每个对象引用的一个点上。

Wow!这很有道理,在我看来,JS似乎更强大了。@DarkLightA:也许应该读一下原型继承:等等,这里使用的UserException.prototype.toString在哪里?抛出新的UserExceptionValue太高;见下面我的评论。当错误为“警报”或类似错误时,可能会隐式调用它。等等,这里使用的UserException.prototype.toString在哪里?抛出新UserExceptionValue过高;。toString是一个本机JS函数,可以通过多种方式隐式调用,将两个字符串关联在一起,尝试通过警告、记录等方式“打印”对象,那么这里使用的UserException.prototype.toString在哪里呢?抛出新的UserExceptionValue太高@当连接或打印该对象时,将隐式调用DarkLightA.toString。
alert(user_exception); //alerts UserException: Error
throw new UserException("Value too high!");