更改<对象>.原型的实例方法(通过上下文)

Change <Object>.prototype from its instance method (via context)

本文关键字:上下文 实例方法 原型 lt 对象 gt 更改      更新时间:2023-09-26

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

我所写的(到目前为止):

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,但我不知道该用什么。

EDIT-用法:

这只是我脑海中浮现的概念。我在Angular 1.5服务中使用它。服务本身用于驱动表单向导。用户可以更改表单中的各种内容,其中很少有内容会在整个表单向导中引起较大的更改。

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

我创建多个依赖实例并从服务返回它们。然后,当我用户更改"核心"输入时,为实例父对象更改原型,它为您做其他一切。

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

正如我所评论的,您不能使用函数的实例来更改它的原型。这就像使用它的对象来改变类结构。这是不可能的。

即使您尝试重写prototype中的属性,也不会在prototype中重写它,而只会添加一个本地属性。

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();

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

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

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