JSON方式来编写对象
简单 ?不适合多个对象
var json={a:12,
?????????show:function (){
?????????????alert(this);
?????????}
};
json.show(); //理所当然弹出的是object(this指的是json)
call函数
function show(){ ???alert(this);}show();//windowshow().call();//和上面的一样也是弹出window call()其实就是调用函数 但又和普通的函数调用有区别show().call(12);//alert 12而不是‘this‘(window) 即call可以改变函数执行时的thisfunction show(a,b){ ???alert(‘this是:‘+this+‘\na是:‘+a+‘\nb是:‘+b);}show(12,5);//弹出window 12 5show.call(‘abc‘,12,5);//只需把第一个参数变成this 后面的还是实参给形参
var arr1=[1,2,3];var arr2=arr1;//这样也是引用 ?而不是单单的复制//改变方法:var arr3=[];for(var i=0;i<arr.length;i++){ ????arr3.push(arr1[i]);}arr3.push(4);
对象由属性(变量)和方法(函数)构成
<script>function A(){ ????this.abc=12;}A.prototype.show=function (){ ?????alert(this.abc);}//继承Afunction B(){ ???//这个this 是指的new B() ?这是处在形参位置上的哇 ???A.call(this); ???//call()其实就是调用函数 但又和普通的函数调用有区别即call可以改变函数执行时的this ???//通过call来继承属性}B.prototype=A.prototype;//继承"方法" ?原型这个也是引用!(c语言里的值传递啊引用传递啊) (下面改正)B.prototype.fn=function (){ ???alert(‘abc‘);}var objB=new B();var objA=new A();alert(obj.abc);//12obj.show();objA.fn();//弹出了对象 按理来说A是没有这个方法的 但是call()这个是引用传递</script>//改正方法: ????for(var i in A.prototype){ ????????B.prototype[i]=A.prototype[i]; ????}
拖拽 面向对象形式
<!DOCTYPE html><html><head><meta ?charset="utf-8"><title>diyici</title><style>#div1{ width:200px; height:200px; background:yellow; position:absolute;}</style><script>window.onload=function(){ ???new Drag(‘div1‘);}function Drag(id){ ???var _this=this; ???this.disX=0; ???this.disY=0; ???this.oDiv=document.getElementById(id); ???this.oDiv.onmousedown=function (ev){ ???????????_this.fnDown(ev); ???}}Drag.prototype.fnDown=function (ev){ ???????var _this=this; ???????var oEvent=ev||event; ????????this.disX=oEvent.clientX-this.oDiv.offsetLeft; ????????this.disY=oEvent.clientY-this.oDiv.offsetTop; ???????document.onmousemove=function (ev){ ????????????_this.fnMove(ev); ???????} ???????document.onmouseup=function (){ ???????????_this.fnUp(); ???????}}Drag.prototype.fnMove=function (ev){ ???????var _this=this; ???????var oEvent=ev||event; ???????this.oDiv.style.left=oEvent.clientX-this.disX+‘px‘; ???????this.oDiv.style.top=oEvent.clientY-this.disY+‘px‘;}Drag.prototype.fnUp=function (){ ???????document.onmousemove=null; ???????document.onmouseup=null;}</script></head><body> ???????<div id="div1"></div></body></html>
js面向对象实例
原文地址:https://www.cnblogs.com/yundong333/p/10469489.html