扩展对象字面量 [英] Extending object literal
问题描述
var x = {
name: "japan",
age: 20
}
x.prototype.mad = function() {
alert("USA");
};
x.mad();
上面的代码不起作用.对象字面量不能扩展?或 x.mad()
不是正确的调用方式.
The above code does not work.
object literals cannot be extended? or x.mad()
not the right way to call.
推荐答案
你不能这样做.为了能够使用它的 prototype
定义对象方法和属性,您必须将对象类型定义为构造函数,然后使用 new
运算符创建它的实例.>
You can't do it this way. To be able to define object methods and properties using it's prototype
you have to define your object type as a constructor function and then create an instance of it with new
operator.
function MyObj() {}
MyObj.prototype.foo = function() {
// ...
}
var myObj = new MyObj();
myObj.foo()
如果您想继续使用对象字面量,将行为附加到您的对象的唯一方法是像这样将其属性创建为匿名函数
If you want to keep using object literals, the only way to attach behaviour to your object is to create its property as anonymous function like so
var myObj = {
foo: function() {
// ...
}
}
myObj.foo();
后一种方式最快.第一个是在相同类型的多个对象之间共享行为的方式,因为它们将共享相同的原型.后一种方法为您创建的每个对象创建一个函数 foo
的实例.
The latter way is the quickest. The first is the way to share behaviour between mutiple objects of the same type, because they will share the same prototype. The latter way creates an instance of a function foo
for every object you create.
这篇关于扩展对象字面量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!