栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在JS Revealing原型模式中实现继承?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在JS Revealing原型模式中实现继承?

Javascript中没有受保护的变量/属性。但是,当您在同一范围内声明继承类时,可以重用“私有”变量,当私有变量只是原型的“隐藏实用程序”时,这似乎是可能的。

MyNamespace.Person = function Person(params) {    // private variables and functions, individual for each Person instance    var anything, id;    function execute_something() {}    // public properties:    this.name = "";    this.getId = function getId(){        // called a "privileged function", because it has access to private variables    }}MyNamespace.American = function(params) {    MyNamespace.Person.call(this, params); // inherit name and getId()}(function() { // new scope for    // hidden utility functions and other private things    function foo() { }    function helpJSON() { }    function fromJSON() { }    var bar;    (function(personProto) { // new scope for prototype module (not explicitly needed)        // "private" /static/ variables (and functions, if you want them private)        var personCount = 0;        personProto.clone = function clone() { return this.constructor(myself); // or something        };        personProto.toJSON = function toJSON() { // use of helpJSON()        };        personProto.fromJSON = fromJSON; // direct use    })(MyNamespace.Person.prototype);    (function(amiProto) {        // just the same as above, if needed        amiProto.special = function() { // use foo() and co        };    })( MyNamespace.American.prototype = Object.create(MyNamespace.Person.prototype) );})();

这是Javascript的继承方式,这意味着American的原型从Person的原型自动继承了clone(),toJSON()和fromJSON()函数。当然可以改写了。功能是

new MyNamespace.American() instanceof MyNamespace.Person; // true

当然,如果不需要,并希望使用类似模块的方式,则可以重用实用程序功能,即仅复制它们:

(function() {    // hidden utility functions and other private things    var bar;    var personCount;    function foo() { }    function helpJSON() { }    function fromJSON() { }    function clone() {        return this.constructor(myself); // or something    }    function toJSON() { }    (function(personProto) { // new scope, not really needed        // private variables are useless in here        personProto.clone = clone;        personProto.toJSON = toJSON;        personProto.fromJSON = fromJSON;    })(MyNamespace.Person.prototype);    (function(amiProto) { // new scope, not really needed        // copied from personProto        amiProto.clone = clone;        amiProto.toJSON = toJSON;        amiProto.fromJSON = fromJSON;        // and now the differences        amiProto.special = function() { // use foo() and co        };    })(MyNamespace.American.prototype);})();


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/391569.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号