Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

javascript - JavaScript .prototype如何工作?(How does JavaScript .prototype work?)

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.(这些幻灯片也确实起到了很大作用。)

  ask by John Leidegren translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...