从对象生成类(JavaScript)
我试图从JavaScript中的对象生成一个类。例如:从对象生成类(JavaScript),javascript,class,object,Javascript,Class,Object,我试图从JavaScript中的对象生成一个类。例如: var Test = { constructor: function() { document.writeln('test 1'); }, method: function() { document.writeln('test 2'); } }; var TestImpl = function() { }; TestImpl.prototype.constructor = Test.constructor; TestImp
var Test = {
constructor: function() { document.writeln('test 1'); },
method: function() { document.writeln('test 2'); }
};
var TestImpl = function() { };
TestImpl.prototype.constructor = Test.constructor;
TestImpl.prototype.method = Test.method;
var x = new TestImpl();
x.method();
但这不起作用:它只会编写“test2”(不管出于什么原因,构造函数没有被正确定义)。为什么?您的TestImpl函数是构造函数。通常你会这样做:
var Test1 = function () {
document.writeln('in constructor');
};
Test1.prototype = {
x: 3,
method1: function() { document.writeln('x='+this.x); }
}
var y1 = new Test1();
y1.method1();
y1.x = 37;
y1.method1();
var y2 = new Test1();
y2.method1();
y2.x = 64;
y2.method1();
我觉得你有点倒退。通常,您会将原型分配给构造函数,而不是将构造函数分配给原型
将方法分配给构造函数的原型而不是构造函数中的“this”对象的原因是前者只创建一个共享函数,而后者创建函数的单独实例。如果您创建了很多对象,每个对象都有很多方法,那么这一点很重要(将内存分配保持在合理的范围内)。我认为您做得不对 记住,JavaScript实际上根本没有类。它有原型。因此,您真正想要做的是创建一个原型对象,它的工作方式类似于在另一个对象上构建的函数集合。我想不出有什么有用的目的--你能详细说明一下你想做什么吗 尽管我认为您可以通过使用以下方法来实现:
var TestImpl = function() {
Test.constructor.apply(this);
};
TestImpl.prototype.method = Test.method;
Javascript没有“类”的概念,它完全是关于原型和您使用它们的方式[您可以用这个简洁的特性模拟任何类型的继承。]
在javascript中,“函数”扮演[类、方法和构造函数]的角色
因此,为了在Javascript中创建“类”行为,您需要做的就是使用“函数”的强大功能
现在,关于JS的一个优点是,您可以通过使用相同的方法轻松创建“继承”行为。你所需要做的就是将第二级“原型链”连接到第一级,如何连接
B = function(){
this.prototype = new A(); // Connect "B"'s protoype to A's
}
B.prototype.newMethod = function() { alert('testing'); }
var b = new B();
b.method(); // Doesn't find it in B's prototype,
// goes up the chain to A's prototype
b.newMethod(); // Cool already in B's prototype
// Now when you change A, B's class would automatically change too
A.prototype.method = function(){ alert('bleh'); }
b.method(); // alert('bleh')
如果你需要更多的参考资料,我建议你看看
Happy JS ing.打字错误:名称不符。测试/测试
var A = function(){
alert('A.Constructor');
}
A.prototype = {
method : function(){
alert('A.Method');
}
}
var b = new A(); // alert('A.Constructor');
b.method(); // alert('A.Method');
B = function(){
this.prototype = new A(); // Connect "B"'s protoype to A's
}
B.prototype.newMethod = function() { alert('testing'); }
var b = new B();
b.method(); // Doesn't find it in B's prototype,
// goes up the chain to A's prototype
b.newMethod(); // Cool already in B's prototype
// Now when you change A, B's class would automatically change too
A.prototype.method = function(){ alert('bleh'); }
b.method(); // alert('bleh')