码迷,mamicode.com
首页 > Web开发 > 详细

JS -- 实现面向对象

时间:2015-08-09 20:38:14      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

JS – 实现面向对象

JS – 实现面向对象

公有和私有

function Person() {
    var name = "abc";         // private
    var age = 100;            // private

    this.show = function() {  // 公有方法, 要访问私有变量只能这么做
        window.alert(‘name = ‘ + name);
    };
    function f() { alert(‘这是一个私有方法‘); }
}
p.new_func = function() {
    document.write(‘I want to access to private FAIL‘);
    alert(p.name);          // undefined
};
p.new_func();

继承

通过原型实现继承

function tiger() {
}

function cat() {
    this.climb = function () {
        alert(‘cat cat‘);
    }
}

tiger.prototype = new cat();

var t1 = new tiger();
var c1 = new cat();
t1.climb();

对象冒充

function Animal(name, age) {
    this.name = name;
    this.age = age;
}

function Dog(name, age) {
    this.animal = Animal;
    this.animal(name, age);
}
var dog = new Dog(‘a dog‘, 2);
document.write(Dog.name);

if (Dog instanceof Animal) {
    alert(‘Dog 是 Animal 的实例‘);       // 
}

对象复制

function cat() {
    this.climb = function () {
        alert(‘cat cat‘);
    }
}

function tiger() {
    this.extend = function (parent) {
        for (var key in parent) {
            this[key] = parent[key];
        }
    }
}

var t1 = new tiger();
t1.extend(new cat());
t1.climb();

通过 call/apply 实现 对象继承

function Stu(name, age) {
    this.name = name;
    this.age = age;

    this.show = function () {
        alert(this.name + ‘ age is ‘ + this.age);
    }
}

function MidStu(name, age) {
    Stu.call(this, name, age);
}

var m = new MidStu(‘one‘, 23);
m.show();
function cat() {
    this.climb = function () {
        alert(‘cat cat‘);
    }
}

function tiger() {
    this.parent = cat;
    this.parent.apply(this, arguments);
    delete this.parent;
}

var t1 = new tiger();
var c1 = new cat();
t1.climb();
function Dog() {
    Dog.prototype.shout = function () {
        document.write("wang wang wang");
    };
}

var dog = new Dog();
dog.shout();
// 给 array 增加一个 find 方法
Array.prototype.find = function(val) {
    var len = this.length;
    for (var i = 0; i < len; i++) {
        if (val == this[i]) {
            return i;
        }
    }
};

原形

原型的好处: 不会重复创建新的方法, 新的属性, 节省内存

function Dog(name) {
    this.name = name;
    this.func = function () {
        alert(‘....‘);
    };
}

var dog1 = new Dog(‘aa‘);
var dog2 = new Dog(‘bb‘);
if (dog1.func == dog2.func) {   // 输出不相等
    alert(‘相等‘);
} else {
    alert(‘不相等‘);
}


Dog.prototype.func2 = function() {
    alert(‘new fun‘);
};

var dog3 = new Dog(‘aa‘);
var dog4 = new Dog(‘bb‘);
if (dog3.func2 == dog4.func2) { // 输出相等
    alert(‘相等‘);
} else {
    alert(‘不相等‘);
}

TODO 工厂方法

// 如果对象只有一个的时候可以这样用, 不被继承... (工厂方法)
var p = new Object();
p.name = ....
p.age = ...

JS -- 实现面向对象

标签:

原文地址:http://www.cnblogs.com/sunznx/p/4716174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!