有什么区别
var A = function () {
this.x = function () {
//do something
};
};
Run Code Online (Sandbox Code Playgroud)
和
var A = function () { };
A.prototype.x = function () {
//do something
};
Run Code Online (Sandbox Code Playgroud) 我试图了解这种名为JavaScript的黑色艺术 - 而且,我必须承认,对此非常兴奋.我一直在寻找代码示例,主要来自"easeljs",因为这是我将主要使用的.我有点困惑..
我(我想)理解使用prototypefor函数或属性作为class变量和this.someProp用于'实例'变量之间的区别(是的,我知道JavaScript中没有类.)
我看过的代码,我用作自己代码的模板,declare prototype变量然后用它来引用它们
在构造函数中:
this.name = name;
Run Code Online (Sandbox Code Playgroud)
然后声明:
Object.prototype.name;
Run Code Online (Sandbox Code Playgroud)
然后,
this.name = "Freddy";
Run Code Online (Sandbox Code Playgroud)
这是在使用'new'调用的函数内,所以在这种情况下,据我所知,它this指的是当前对象.令我困惑的是原型声明正在做什么以及为什么我们将它用于实例变量?
澄清:在下面的代码中,我没有看到radius的原型声明实现了什么:
(function(){
// constructor
function MyCircle(radius){
this.radius = radius;
}
MyCircle.prototype.radius;
this.area = function(){
return 3.14*this.radius*this.radius;
};
window.MyCircle = MyCircle;
}());
Run Code Online (Sandbox Code Playgroud) 我在尝试让类变量在javascript中工作时遇到了一些麻烦.
我以为我理解了原型继承模型,但显然不是.我假设由于原型将在对象之间共享,因此它们的变量也是如此.
这就是为什么这段代码让我困惑的原因.
实现类变量的正确方法是什么?
function classA() {};
classA.prototype.shared = 0;
a = new classA;
//print both values to make sure that they are the same
classA.prototype.shared;
a.shared;
//increment class variable
classA.prototype.shared++;
//Verify that they are each 1 (Works)
classA.prototype.shared;
a.shared;
//now increment the other reference
a.shared++;
//Verify that they are each 2 (Doesn't Work)
classA.prototype.shared;
a.shared;
Run Code Online (Sandbox Code Playgroud)
更新:所以似乎每个人都在确认通过递增实例的变量这一事实我们不会影响原型.这很好,这是我在我的例子中记录的内容,但这不是在语言设计中出现错误吗?为什么这种行为是可取的?我觉得奇怪的是,当实例的var未定义时,我们遵循原型的隐藏链接,我们得到var的值,但我们将它复制到实例对象中.
我也明白这不是java/c ++/ruby/python,它是一种不同的语言.我只是好奇为什么这种行为可能会很好.