将原型添加到JavaScript Object Literal [英] Adding Prototype to JavaScript Object Literal

查看:116
本文介绍了将原型添加到JavaScript Object Literal的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

STORE = {
   item : function() {
  }
};
STORE.item.prototype.add = function() { alert('test 123'); };
STORE.item.add();

我一直想弄清楚这有什么问题。为什么这不起作用?但是,当我使用以下内容时它可以工作:

I have been trying to figure out what's wrong with this quite a while. Why doesn't this work? However, it works when I use the follow:

STORE.item.prototype.add();


推荐答案

原型对象用于 构造函数 ,基本上是将使用的函数用于创建新对象实例的新操作员

JavaScript中的函数是一等对象,这意味着您可以添加成员并将其视为普通对象:

Functions in JavaScript are first-class objects, which means you can add members to them and treat them just like ordinary objects:

var STORE = {
   item : function() {
  }
};

STORE.item.add = function() { alert('test 123'); };
STORE.item.add();

如前所述,原型对象的典型用法是通过调用a实例化对象使用new运算符的构造函数,例如:

A typical use of the prototype object as I said before, is when you instantiate an object by calling a constructor function with the new operator, for example:

function SomeObject() {} // a constructor function
SomeObject.prototype.someMethod = function () {};

var obj = new SomeObject();

SomeObject的所有实例都将从 SomeObject.prototype <继承成员/ code>,因为这些成员将通过原型链访问。

All the instances of SomeObject will inherit the members from the SomeObject.prototype, because those members will be accessed through the prototype chain.

JavaScript中的每个函数都有一个原型对象,因为无法知道哪些函数旨在用作构造函数。

Every function in JavaScript has a prototype object because there is no way to know which functions are intended to be used as constructors.

这篇关于将原型添加到JavaScript Object Literal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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