2012-03-12 52 views
1

我对JavaScript比较陌生,我来自C#背景。有趣的是,它看起来像今天早些时候有人遇到同样的问题,我有:Serializing a Child Object Within a Parent Object in JavaScript从C#到JavaScript - 使用类实例

基本上,我无法弄清楚如何在对象已经通过序列化后有实例级别的方法。这甚至有可能吗?如果是这样,怎么样?我真的很感兴趣的是某人如何调用MyChild实例上的“测试”方法,该实例是MyParent上的一个属性值。如果你不能这样做,说JS支持OO是否公平?在我看来,这似乎是一种常见的情况。我有点惊讶,我无法在网上找到一个例子,而是偶然发现了上面列出的帖子。

+2

请发布一个显示问题的示例 – 2012-03-12 22:06:20

+0

在我提供的链接中有一个示例。我认为如果有人回答那个人(或女孩的) – user609886 2012-03-12 22:18:14

+0

JavaScript *不是* OO语言,那么有人可以得到两个问题,而不是一个问题,所以公平地说它不支持它。 – Stoive 2012-03-12 22:57:10

回答

2

欢迎来到世界的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”。