English 中文(简体)
我该如何用手稿落实遗产继承?
原标题:How do I implement inheritance in javascript?

我如何在 Javascript 中实施继承? 我开始使用 Knockout.js 并使用 ViewModels/ page 。 但是, 我有一些功能/ 代码, 我希望它能在所有 Vavascript 中共享 。

我在想,在这种情况下,我如何落实继承权呢?

最佳回答

继承不一定是答案。 为什么不为每个视图模式应该采用的所有方法创建一个对象字典。 我对击倒不熟悉, 但这里是您如何在本地js 中做到这一点 。

    var sharedMethods = {
             run: function () {},
             jump: function () {}
        };

    function Person () {};
    // Use jQuery s extend method
    // Now person has run, jump, and talk
    $.extend(Person.prototype, sharedMethods, {
        talk: function () {}
    });
问题回答

JavaScript 提供原型继承。 对象确实从其他物体继承。 这对方法继承可能很好, 但对于财产继承无效 。

通常您可以使用的继承方法 :

function BaseViewModel() { 
   var self = this;
   self.name = ko.observable();
时 时

function Person() {
   var self = this;
   self.firstname = ko.observable();
时 时

Person.prototype = new BaseViewModel();

但这使得所有人与原型共享相同的对象。 当您更改一个人的名称时, 数值会传播给所有人 。 我倾向于使用 jQuery s < strong > extend 方法 。

function Person() {
   var self = this;
   $.extend(self, new BaseViewModel());

   self.firstname = ko.observable();

时 时

这样, BaseViewModel 的值就会被复制到人身上 。

Here s the link from crockford.com
Its the best place to know anything about object oriented Javascript.
Though his methods are little complex to understand at first. Its one of the best best resource as he is best known for his ongoing involvement in the development of the JavaScript language, for having popularized the data format JSON (JavaScript Object Notation), and for developing various JavaScript related tools such as JSLint and JSMin.





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签