是否可以在javascript中为现有对象分配原型?

编程入门 行业动态 更新时间:2024-10-22 20:43:39
本文介绍了是否可以在javascript中为现有对象分配原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我有:

function Base (){ this.sayHi = function(){ alert('hi'); } } function Thing (val){ this.value = val; } var bob = new Thing("bob");

我现在有什么方法可以说bob继承自Base以便我可以调用:

Is there some way I can now say that bob inherits from Base so that I could call:

bob.sayHi();

基本上可以在该实例上使用Base类的所有方法和属性吗?

Basically have all the methods and properties of the Base class available on that instance?

基于CMS帖子的解决方案的更相关示例:

此处的项目可能代表返回的数据服务器..

Here Items could represent data returned by the server..

var Items = [ { sku: 123, type:'buggy', title:'This is a title', description: 'this is a description' }, { sku: 234, type: 'baby-monitor', title: 'This is a title 2', description: 'this is a description 2' } ] function ItemMethods() { this.BannerHTML = function () { return '<div class="banner _item_' + this.type + '_' + this.sku + '"><h2>' + this.title + '</h2><p>' + this.description + '</p></div>'; }; } Items.GetBySKU = function (code) { for (var i = 0; i < Items.length; i++) { if (Items[i].sku == code) { return Items[i]; } } }; $.each(Items, function (i, item) { ItemMethods.apply(item); }); alert(Items.GetBySKU(234).BannerHTML());

任何进一步的评论或解决方案都很乐意接受..总是对问题的潜在解决方案感兴趣; - )

Any further comments or solutions gladly accepted.. always interested in potential solutions to a problem ;-)

推荐答案

请注意,您在构造函数中创建的属性与构造函数的 prototype ,它们是您使用 new Base(); 创建的对象的自己的属性,它们不会被继承。但是,我想你想要在 Thing <新创建的对象上应用 Base 构造函数。 / code>:

Note that the properties that you create within the constructor, have nothing to do with the constructor's prototype, they are own properties of the object you create using new Base();, they are not inherited. However, I think what you want to do it to apply the Base constructor function on the newly created object of Thing:

function Base (){ this.sayHi = function(){ alert('hi'); } } function Thing (val){ Base.apply(this, arguments); this.value = val; } var bob = new Thing("bob"); bob.sayHi();

请注意 bob 不会继承 Base (它无法访问添加到 Base.prototype 的属性)

Note that bob will not inherit from Base (it won't have access to properties added to Base.prototype)

bob instanceof Base; // false bob instanceof Thing; // true

更多推荐

是否可以在javascript中为现有对象分配原型?

本文发布于:2023-10-31 04:16:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544975.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原型   中为   分配   对象   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!