问题:
I'm not that into dynamic programming languages but I've written my fair share of JavaScript code. 我不喜欢动态编程语言,但是我写了相当一部分JavaScript代码。 I never really got my head around this prototype-based programming, does any one know how this works? 我从来没有真正了解过这种基于原型的编程,有人知道它是如何工作的吗?
var obj = new Object();
obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();
I remember a lot discussion I had with people a while back (I'm not exactly sure what I'm doing) but as I understand it, there's no concept of a class. 我记得很久以前与人们进行过多次讨论(我不确定自己在做什么),但是据我了解,这里没有一个课堂的概念。 It's just an object, and instances of those objects are clones of the original, right? 这只是一个对象,这些对象的实例是原始对象的副本,对吗?
But what is the exact purpose of this ".prototype" property in JavaScript? 但是,此“ .prototype”属性在JavaScript中的确切目的是什么? How does it relate to instantiating objects? 它与实例化对象有何关系?
Update: correct way 更新:正确的方法
var obj = new Object(); // not a functional object
obj.prototype.test = function() { alert('Hello?'); }; // this is wrong!
function MyObject() {} // a first class functional object
MyObject.prototype.test = function() { alert('OK'); } // OK
Also these slides really helped a lot. 这些幻灯片也确实起到了很大作用。
解决方案:
参考一: https://stackoom.com/question/2P2H/JavaScript-prototype如何工作
参考二: https://oldbug.net/q/2P2H/How-does-JavaScript-prototype-work