js中的简单问题(静态属性和实例属性):function Rectangle(w,h)
{
this.width=w;//问题:this.width是相当于Rectangle.width还是Rectangle.prototype.width?
this.height=h;
}问题:this.width是相当于Rectangle.width还是Rectangle.prototype.width?
能否说下原理
{
this.width=w;//问题:this.width是相当于Rectangle.width还是Rectangle.prototype.width?
this.height=h;
}问题:this.width是相当于Rectangle.width还是Rectangle.prototype.width?
能否说下原理
答:不是例如
function Rectangle(){};
Rectangle.width = '10';
Rectangle.height = '10';
//这么写才是Rectangle.width;还是Rectangle.prototype.width?
答:也不是例如这么写
function Rectangle(){};
Rectangle.prototype.width = '10';
Rectangle.prototype.height = '10';
你这么写就好比JAVA的构造函数
function Rectangle(w,h)
{
this.width=w;
this.height=h;
}//这样调用
var rectangle = new Rectangle('10','10');
rectangle.width; //这样访问width
rectangle.htight; //这样访问height
alert(xo.width); //结果显示 300
function Rectangle(){};
Rectangle.width = '10';
Rectangle.height = '10';
//这么写才是Rectangle.width; 也就是静态属性例如这么写,是原型属性
function Rectangle(){};
Rectangle.prototype.width = '10';
Rectangle.prototype.height = '10';
你这么写就好比JAVA的构造函数,也就是实例属性
function Rectangle(w,h)
{
this.width=w;
this.height=h;
}//这样调用
var rectangle = new Rectangle('10','10');
rectangle.width; //这样访问width
rectangle.htight; //这样访问height
如果相当于Rectangle.width的话,是静态属性,
可以这样调用alert(Rectangle.width);
但这样调用报错
function Rectangle(){};
Rectangle.width = '10';
Rectangle.height = '10';
//这么写才是Rectangle.width; 也就是静态属性
function Rectangle(w,h)
{
this.width=w;
alert(this.width);
this.height=h;
alert(this.height);
}var rectangle = new Rectangle('10','10'); //输出"10""10"
var rectangle1 = new Rectangle('20','20'); //输出"20""20" this总是指向调用该函数的实例对象
</script>
就像楼上所说的,this总是指向调用该函数的实例对象