嗨,
我有一个用对象字面语法编写的JavaScript程序:
var MyJsProgram = {
someVar: value1,
somevar2: value2,
init : function() {
//do some initialisation
},
libraryFunction : function() {
},
getStyle : function() {
},
extend : function() {
}
}可以同时运行此脚本的多个实例。我是否应该将常用方法移到myJsProgram的原型对象中?如果是的话,这个语法正确吗?
var MyJsProgram = {
someVar: value1,
somevar2: value2,
init : function() {
//do some initialisation
},
//more methods/members here that are unique to each instance
}
myJsProgram.prototype = {
//all shared methods here
}发布于 2010-10-21 13:29:09
不,那个语法不正确(无意冒犯) ;)
您需要创建一个使用其原型的对象。这意味着您需要一个构造函数(它是JavaScript中的一个函数)。适用于你的问题:
var MyJsProgram = function (value1, value2) {
// "this" refers to the current instance of this object
this.someVar = value1;
this.someVar2 = value2;
// do some initialization
};创建如下新对象:
var jsProgramInstance = new MyJsProgram(value1, value2);原型是这些对象的实例成员。它们的定义如下:
MyJsProgram.prototype.someSharedMethodName = function () {
// do shared method stuff here
// (this.someVar and this.someVar2 are available here)
};这样使用它们(在以前创建的实例上):
jsProgramInstance.someSharedMethodName();您应该而不是执行以下操作,因为它覆盖了可能存在的现有原型属性(由于继承):
MyJsProgram.prototype = {
someSharedMethodName: function () {
// ...
},
// ...
};发布于 2010-10-21 13:32:46
首先,创建一个函数,您可以从中创建实例。
// Make it a function, so you can make a new instance
var stdProgram = function(){};
// All shared methods go here
stdProgram.prototype = {
echo: function(message){
alert(message);
},
extend: function(key, value){
this[key] = value;
}
};然后,您就可以创建特定的“程序”,实际上只是基类的实例。
// And here you can make instances for specific programs
var myFirstProgram = new stdProgram(),
mySecondProgram = new stdProgram();
myFirstProgram.extend('unique', function(){
alert('I am unique');
});
mySecondProgram.aVar = 'test';要确保一切正常运行,请尝试如下:
myFirstProgram.unique(); // Should alert I am unique
mySecondProgram.unique(); // Should throw an error, unique is undefined
alert(mySecondProgram.aVar); // Should alert test
alert(myFirstProgram.aVar); // Should echo undefined
myFirstProgram.echo('hi'); // Should alert hi
mySecondProgram.echo('hi'); // Should alert hihttps://stackoverflow.com/questions/3987851
复制相似问题