js面向对象编程笔记

1. 基础

面向对象实例

function Lecture(name, teacher) {
  this.name = name;
  this.teacher = teacher;
}
Lecture.prototype.display = function () {
  return this.teacher + ' is teaching ' + this.name;
}
//var le = new Lecture('数学', '李四');
//console.log(le.display());

function Schedule(lectures) {
  this.lectures = lectures;
}
Schedule.prototype.display = function () {
  var str = '';
  for (var i = 0; i < this.lectures.length; i++) {
    str += this.lectures[i].display() + '
';
  }
  return str;
}
var sc = new Schedule([
new Lecture('yuwen', 'aaa'),
new Lecture('shuxue', 'bbb'),
new Lecture('wuli', 'ccc')
]);
sc.display();
View Code

操作页面元素实例

<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
    var lis = document.getElementsByTagName('li');
    for (var i = 0; i < lis.length; i++) {
        lis[i].style.border = '1px solid #f00';
    }
    var item1 = document.getElementById('item1');
    item1.parentNode.removeChild(item1);
}
</script>
</head>
<body>
<ul>
    <li id="item1">item1</li>
    <li id="item2">item2</li>
    <li id="item3">item3</li>
    <li id="item4">item4</li>
</ul>
</body>
</html>
View Code

鼠标移入移出事件实例

        lis[i].onmouseover = function() {
            this.style.backgroundColor = 'blue';
        }
        lis[i].onmouseout = function() {
            this.style.backgroundColor = 'white';
        }

2. 面向对象

对象是javascript的基本单位,js中的一切都是对象。下面介绍引用、作用域、闭包以及上下文。

引用就是指向对象实际位置的指针。

作用域就是变量的有效区域,在js中作用域由函数约束而不是由块约束。

闭包表示内部的函数可以引用包含它的外层函数中定义的变量,即使外层函数已经执行完毕。

上下文通过变量this工作。变量this总是引用代码当前所在的那个对象。

3. 设计模式

3.1 观察者模式

var Subject = function() {
    this.observers = [];
    this.attach = function(observer) {
        this.observers.push(observer);
    }
    this.detach = function(observer) {
    }
    this.notify = function() {
        for (var i = 0; i < this.observers.length; i++) {
            this.observers[i].update();
        }
    }
}
var Observer = function(name) {
    this.name = name;
    this.update = function(args) {
        console.log('observer name: ' + name);
    }
}
var sub= new Subject();
sub.attach(new Observer('aaa'));
sub.attach(new Observer('bbb'));
sub.attach(new Observer('xiaoming'));
sub.notify();
sub.attach(new Observer('xiaohong'));
sub.notify();

原文地址:https://www.cnblogs.com/feilv/p/4518757.html