js难题,谁会?

Luskyle 2017-03-19 07:39:08

定义一个js函数,
function a()
{
this.v1=0;
this.v2="hello";

function b()
{

}


}

实例化a方法
var xx=new a();

可以这样访问 a 中的变量,
xx.v1;

现在问题是:有什么方法可以实现当
v1的值改变时调用b函数?

如此改变v1的值
xx.v1=8;
...全文
136 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Luskyle 2017-03-19
  • 打赏
  • 举报
回复
额,我的疏忽。问题已经解决了
Luskyle 2017-03-19
  • 打赏
  • 举报
回复
function DrawLine() { //默认值 this.startx=0; this.starty=0; this.endx=0; this.endy=0; this.lineColor="#000000"; this.lineCap="butt"; Object.defineProperties(this,"lineCap",{ set:function(v){ lineCap=v; b(v); }, get:function(){ return lineCap; } }) function b(v) { console.log("b函数被调用了",v); } this.SetLineCap=function (cap) { lineCap=cap; DrawLineDefaultColor(this.startx,this.starty,this.endx,this.endy); } this.SetLineColor=function (color) { lineColor=color; DrawLineSelfDefinedColor(this.startx,this.starty,this.endx,this.endy,this.lineColor); } this.startx=arguments[0]; this.starty=arguments[1]; this.endx=arguments[2]; this.endy=arguments[3]; var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d");   var len= arguments.length; //获得该函数参数的个数     if(len==4)     {         DrawLineDefaultColor(this.startx,this.starty,this.endx,this.endy);     }     else if(len==5)     { this.lineColor=arguments[4];         DrawLineSelfDefinedColor(this.startx,this.starty,this.endx,this.endy,this.lineColor);              } function DrawLineDefaultColor(startx,starty,endx,endy){ // alert(startx); ctx.beginPath(); ctx.moveTo(startx,starty); ctx.lineWidth=10; ctx.lineCap=this.lineCap; // alert(this.lineCap); ctx.lineTo(endx,endy); ctx.stroke(); } function DrawLineSelfDefinedColor(startx,starty,endx,endy,lineColor){ ctx.strokeStyle=this.lineColor; ctx.beginPath(); ctx.moveTo(startx,starty); ctx.lineTo(endx,endy); ctx.stroke(); } } var xx=new DrawLine(300,50,300,200); xx.SetLineCap("round"); xx.SetLineColor("#A82F2F"); xx.lineCap="round"; alert(xx.lineCap);
Luskyle 2017-03-19
  • 打赏
  • 举报
回复
我觉得你写得很对。但是我得到了异常 Uncaught TypeError: Property description must be an object: l at Function.defineProperties (<anonymous>)
天际的海浪 2017-03-19
  • 打赏
  • 举报
回复

function a()
{
    var v1=0;
    Object.defineProperty(this,"v1",{
	    set: function(v){
			b(v);
	    	v1 = v;
    	},
    	get: function(){
    		return v1;
    	}
    })
    this.v2="hello";
    function b(v)
    {
        console.log("b函数调用了",v);
    }
}
var xx = new a();
xx.v1 = 8;

87,993

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧