如何解决实验:JavaScript实例可以本身就是构造函数并具有自己的一组实例吗?
let bar;
function foo(){
this.x=x;
this.y=y;
}
bar=new foo(1,2);
/*Since all functions in javascript are objects.
Why can't an instance an object be a constructor itself?*/
!function bar(a,b){
this.a=a;
this.b=b;
}(); // (1)
let bar1=new bar(3,4);
console.log(bar1.a);
(1):使用命名的IIFE,bar可以同时作为实例和构造函数吗?
利用语言的自由性看看这是否是一种有趣的技巧,还有其他方法可以做到吗?
解决方法
听起来您正在寻找构造函数返回函数:
function makeBar(x,y) {
function Bar(a,b) {
this.a = a;
this.b = y + b;
}
Bar.x = x;
return Bar;
}
var Bar1 = makeBar("bar1",2);
console.log(Bar1.x); // "bar1"
var myBar1 = new Bar1(1,2); // Bar { a: 1,b: 4 }
console.log(myBar1 instanceof Bar1); // true
var Bar2 = makeBar("bar2",0);
var myBar2 = new Bar2(3,3); // Bar { a: 3,b: 3 }
console.log(myBar2 instanceof Bar1); // false
要使makeBar
不是工厂函数而是具有有效原型的构造函数,您必须使用
function Foo(x,b) {
this.a = a;
this.b = y + b;
}
Object.setPrototypeOf(Bar,Foo.prototype);
Bar.x = x;
return Bar;
}
Foo.prototype.log = function() {
console.log("I'm "+this.name);
};
var Bar = new Foo("bar",2);
Bar.log();
console.log(Bar instanceof Foo); // true
var myBar = new Bar(1,2);
console.log(myBar instanceof Bar); // true
,
JavaScript实例本身是否可以是构造函数并具有自己的一组实例?
当然, function 是Function
的实例,而构造函数是 function 。
所以你可以拥有
const instance1 = new Function("a","this.a = a;");
const instance2 = new instance1("foo");
console.log(instance2.a); // "foo"
如果您需要instance1
不只是一个原始函数,甚至可以扩展此构造函数:
class MyFunc extends Function {
doSomethingMore(){ console.log("I'm doing more"); }
}
const instance1 = new MyFunc("a","this.a = a;");
instance1.doSomethingMore();
const instance2 = new instance1("foo");
console.log(instance2.a); // "foo"
但是我看不出您为什么要这么做的明确原因...
(请注意,与通过函数表达式或语句进行解析时相比,通过Function
构造函数动态创建函数的“性能”通常要差一些。)
在您的代码中,由于bar
是用let
声明的,因此不能在同一范围内将其重新声明为函数声明。
如果要执行此操作,可以让foo
显式返回一个函数,然后可以使用new
进行调用:
function foo(x,y) {
this.x = x;
this.y = y;
return function bar(a,b) {
this.a = a;
this.b = b;
};
}
const bar = new foo(1,2);
const bar1 = new bar(3,4);
console.log(bar1.a);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。