用json方式实现面向对象
var json = {
inin: function(){
this.showAge(),
this.showName()
},
name: 'wen',
age: 28,
showName: function(){
alert(this.name)
},
showAge: function(){
alert(this.age)
}
}
json.inin()
用 json 方式实现面向对象(单体):优点是简单,缺点是多适合多个对象。
命名空间(防止同一函数名会引起冲突)
var inin = {}
inin.common = {}
inin.header = {}
inin.foot = {}
inin.foot.tab = function(){
alert('a')
}
inin.header.tab = function(){
alert('b')
}
inin.common.tab = function(){
alert('c')
}
inin.foot.tab()
inin.header.tab()
inin.common.tab()
继承父级的属性和方法
call 用法
function show(a, b){
alert('this是:'+ this + '\n a是:' + a + '\n b是:' + b)
}
show(12, 5)
show.call('abc', 3, 4) //call里第一个参数可以改变函数执行时的this指向
继承
function A() {
this.abc = 'wen'
}
A.prototype.show = function () {
alert(this.abc)
}
function B() {
A.call(this) //this 指向 new B()
}
//B.prototype = A.prototype //错误用法,因为对象是 引用类型,会相互影响
for(var i in A.prototype){
B.prototype[i] = A.prototype[i]
}
B.prototype.fn = function () {
alert('abc')
}
var objA = new A()
var objB = new B()
objB.show() //wen
objB.fn() //abc
objA.fn() //objA.fn is not a function
子类 可以继承 父类的属性和方法,子类可以添加自己的内容,父类不能使用子类的属性和方法
实例:拖拽和继承
<li>第一步、不能让函数有嵌套,将一部分需要的东西变成全局变量</li>
<li>第二步、将 onload 改成 构造函数</li>
<li>第三步、将全局变量 改成 属性,将函数 改成 方法</li>
<li>第四步、有关 this 指向的修改</li>
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(){
_this.fnDown()
}
}
Drag.prototype.fnDown = function(ev) {
var oEvent = ev || event
var _this = this
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()
}
return false
}
Drag.prototype.fnMove = function(ev) {
var oEvent = event || ev
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.onmousedown = null
}
继承父类拖拽功能并加上限制范围的新功能
function LimitDrag(id) {
Drag.call(this, id)
}
for(var i in Drag.prototype){ // Drag.prototype是json数据
LimitDrag.prototype[i] = Drag.prototype[i]
}
LimitDrag.prototype.fnMove = function (ev) {
var oEvent = event || ev
var l = oEvent.clientX - this.disX
var t = oEvent.clientY - this.disY
if(l < 0){
l = 0
}else if(l > document.documentElement.clientWidth - this.oDiv.offsetWidth){
l = document.documentElement.clientWidth - this.oDiv.offsetWidth
}
this.oDiv.style.left = l + 'px'
this.oDiv.style.top = t + 'px'
}
系统对象
宿主对象:与js的运行环境有关。运行在浏览器上宿主对象是 BOM DOM,node.js 是运行在后台的。
本地对象(非静态对象):Object String Date~
内置对象(静态对象): Math