欢迎来到世界的JavaScript。但首先要做的是,理解JavaScript不是基于OO的语言。实际上,JavaScript是一种基于原型的语言,其中的事情会如何变化,OO行为只是用这种语言来模拟。在这里,我发现了一个很好的问题,并且对“JavaScript是什么”的解释非常清楚。 Link to the question. 还有其他语言,比如LUA,或者是最近的一种IOL语言,它们也是基于原型的语言。 Wikipedia have a good article about it with a list of prototype based languages.
我认为知道这些事情是很重要的,如果你真的想学习JavaScript,这可能会清除一些事情。
现在关于你的问题,目前还不是很清楚这个问题只是关于序列化还是关于JavaScript“OO”如何工作。无论如何,你发布的这个例子代码的这部分看起来很混乱,是的,当你刚刚学习JS时可能会感到困惑。
代码与发表意见,澄清一些点的部分:
//The function declaration that will become the constructor
//There is a reason for the "why" the function is used as the "base prototype"
//for other objects, but this would be a little out of context.
function MyChild() { this.init(); }
//Here you start declaring the prototype of instances from MyChild
//So everything that is in the prototype are like static (from C#) references
//in the objects, for properties, not for functions
MyChild.prototype = {
//Here is the problem of the code of the question that you posted
//The problem is that, when you create a instance from MyChild,
//"data" isn't a instance field, which means that if you change it,
//it will change in every object created from MyChild, this is because
//it is the same reference in all of them
data: {
id: 0,
fullName: "",
},
//Here we have the methods of the instance, when they are called, "this"
//is the object itself, so to access fields of the object you must use "this"
//in order to contextualize the operation, without "this" you are going to access
//the current function/global scope
init: function() {
//since the constructor call this method we can initialize things here
//these are the instance fields, you must set the property in the "this"
this.prop1 = 1;
this.prop2 = 2;
},
save: function (key) {
},
load: function (key) {
},
test: function() {
alert("Testing Child functions");
}
}
出头,这将是很好的了解很容易充分理解JavaScript:基于
- 原型模式/原型的语言,怎么原型作品 (更多关于克隆而非实例化)
- 使用“var”或不是的声明
- 范围,在JavaScript范围内是基于功能而不是基于“{...}”的
- 上下文中,“this”可以在所有JavaScript代码中访问,但它在不同的地方意味着不同的事物。也可以通过调用JS中的某些特殊方法来“设置”“this”。
请发布一个显示问题的示例 – 2012-03-12 22:06:20
在我提供的链接中有一个示例。我认为如果有人回答那个人(或女孩的) – user609886 2012-03-12 22:18:14
JavaScript *不是* OO语言,那么有人可以得到两个问题,而不是一个问题,所以公平地说它不支持它。 – Stoive 2012-03-12 22:57:10