从其实例方法更改<object> .prototype(通过上下文)

时间:2016-01-07 10:34:00

标签: javascript

它应该做什么: 实例上的调用方法应该在不同的原型中变形“构造函数原型”,但保持实例(和所有其他实例)存活

我拥有的(到目前为止):

var differentPrototypeObj = {
    test: function() {
        console.log("it is working");
    }
}

var F = function() {
};

F.prototype = {
    changeMyConstructorPrototype: function() {
        this.constructor.prototype = Object.create(differentPrototypeObj); // doesnt work, but I though it should
        this.constructor.prototype = differentPrototypeObj; // doesnt work, but I though it should
        F.prototype = whatever; // dont want to do this because F is being inherited somewhere and it
    }
};

测试

var f = new F();
f.changeMyconstructorPrototype();
console.log(f.test); // want this to be function, but is undefined
console.log(f.changeMyConstructorPrototype); // want this to be undefined, but is still accessible

我想我的代码是this.constructor.prototype,但我无法弄清楚要使用什么。

编辑 - 用法:

这只是我心中的概念。我在Angular 1.5服务中使用它。服务本身用于驱动表单向导。用户可以在表单中更改各种内容,但很少会在整个表单向导中导致大的更改。

这个大的更改必须使实例保持活动状态,但在表单向导中的(向前和向后)方向上更改了很多行为(主要是输入验证,属性计数和输入可见性)。

我创建了多个依赖实例并从服务中返回它们。然后,当我的用户更改“核心”输入时,将为实例父级更改原型,为您执行其他所有操作。

可以选择不同的方法,但我选择这个作为实验性和有趣的。

2 个答案:

答案 0 :(得分:0)

正如我所评论的那样,您无法使用其实例更改函数的原型。它就像使用其对象改变类结构一样。这是不可能做到的。

即使您尝试覆盖原型中的属性,也不会在原型中覆盖它,但只会添加本地属性。

var differentPrototypeObj = {
    test: function() {
        console.log("it is working");
    }
}

var F = function() {};

function notify (){
  alert("Hello foo");
}

F.prototype = differentPrototypeObj;

// Additional property
F.prototype.notify = notify;

var f = new F();

f.test();
f.notify();


var f1 = new F();
f1.test = function(){
  console.log("This is new function");
}

f1.test();

答案 1 :(得分:0)

解决方案我发现只适用于一个实例而不适用于所有现有实例。

函数是Object.setPrototypeOf()我用作:

F.prototype = {
    changeMyConstructorPrototype: function() {
        Object.setPrototypeOf(this, Object.create(differentPrototypeObj));
    }
};
相关问题