是否可以在javascript中为现有对象分配原型? [英] is it possible to assign a prototype on an existing object in javascript?

查看:95
本文介绍了是否可以在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 <无关/ code>,它们是您使用 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中为现有对象分配原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆