原型对象心得

2017-10-12  本文已影响0人  4d56c320ce84

原型

prototype就是“原型”的意思。每个函数都有原型,原型是一个对象。

找原型对象有2个办法:

  1. 构造函数名.prototype
  2. 对象名.proto

原型的应用

在 Array中 新增1个方法 boomXXX, 可以往里面压入1个元素
Array.prototype.boomXXX = function(a) {
    // this 就是调用此函数的 那个数组对象
    this.push(a)
}

var arr = [1, 2, 3];

arr.boomXXX(4);

// 1,2,3,4  +
console.log(arr);
在 Array 中 新增1个方法 dz, 作用:调转 第1个元素 与 最后1个元素
例如:   a = [1,2,3,4];
             a.dz();
            console.log(a);   // 4,2,3,1
Array.prototype.dz = function() {

    // 取出第1个元素, 因为this相当于是调用的对象
    var a = this[0];
    var b = this[this.length-1];

    // 倒转
    this[0] = b;
    this[this.length-1] = a;
}

var a = [1,2,3,4]

a.dz()

console.log(a);

继承

继承父类的东西,并且可以增加自己的东西
属性 父类.call(this, 参数列表)
方法 子类.prototype = new 父类();

// 动物类
function Animal()
{
    this.name = "动物";
    this.color = "黄色"
}

Animal.prototype.run = function() {
    console.log("跑跑跑")
}

// 因为狗和动物有大部分代码是重复的
function Dog()
{
    this.nose = "大鼻子";
}
// 设置狗的原型对象为 动物,相当于 狗 继承了 动物的所有属性和方法
//   通过这条语句,可以实现让 狗 继承了 动物中的 所有属性和方法
Dog.prototype = new Animal();

var dog1 = new Dog();
dog1.run();

对象冒充

function Cat(n) {
    this.name = n;
}

var obj = {};

// obj 替代里面的this, 称为 对象冒充
Cat.call(obj, "猫猫");

// 猫猫
console.log(obj.name);

上一篇 下一篇

猜你喜欢

热点阅读