您的位置 >>> 星想互联 >>> 编程技术 >>> JQUERY+JS
JS面向对象---封装
点击数:1421  发布时间2018-06-21 22:11:45

概述:

    Javascript是一种基于对象(object-based)的语言,你遇到的所有东西几乎都是对象。但是,它又不是一种真正的面向对象编程(OOP)语言,因为它的语法中没有class(类)。

1.没有为构造函数设置其原型对象属性

// 构造函数

function cat (name, color) {
    this.name = name;
    this.color = color;
    this.type = 'TYPE';
    this.eat = function () {
        console.log('eat')
    }
}

// 实例对象1
var cat1 = new cat('cat1_name', 'cat1_color');
//console.log(cat1.constructor ==  cat) // cat1含有一个constructor属性自动指向它们的构造函数
//console.log(cat1 instanceof cat) // 验证原型对象和实例对象之间的关系

// 实例对象2
var cat2 = new cat('cat2_name', 'cat1_color');
//console.log(cat2 instanceof cat) // 验证原型对象和实例对象之间的关系

console.log(cat2.type === cat1.type) // true (这里有些疑惑)

//console.log(cat2.eat == cat1.eat) // false

2.为构造函数设置其原型对象属性

// 构造函数
function cat (name, color) {
    this.name = name;
    this.color = color;
}
// 构造函数的原型对象
cat.prototype.type = 'PROTOTYPE TYPE';
cat.prototype.eat = function() {
    console.log('PROTOTYPE EAT');
}
// 实例对象1
var cat1 = new cat('cat1_name', 'cat1_color');

// 实例对象2

var cat2 = new cat('cat2_name', 'cat1_color');

console.log(cat2.type === cat1.type) // true  ★★
console.log(cat2.eat === cat1.eat) // true  ★★

3.构造函数的方法

3.1 isPrototypeOf()

这个方法用来判断,某个proptotype对象和某个实例之间的关系。

alert(Cat.prototype.isPrototypeOf(cat1)); //true

alert(Cat.prototype.isPrototypeOf(cat2)); //true

3.2 hasOwnProperty(test_property) 

这个方法用来判断一个属性(test_property)是否是实例对象的本地属性、或者是继承自构造函数的原型对象(prototype)的属性。

      alert(cat1.hasOwnProperty("name"))  // true

      alert(cat1.hasOwnProperty("type")) // false

3.3 in 运算符

    3.3.1 in 运算符 可以直接判断:某个实例对象是否含有某个属性,不管是不是本地属性

        console.log("name" in cat1) // true
        console.log("type" in cat1) // true
        console.log("eat" in cat1) // true

    

    3.3.2 in 运算符可以遍历对象中的每个属性

        for (var key in cat1) {
            console.log(key + ' == ', cat1[key])

        }

        打印结果:

            name ==  cat1_name
            color ==  cat1_color
            type ==  PROTOTYPE TYPE
            eat ==  function () {
                console.log('PROTOTYPE EAT');
            }
来源:咸宁网站建设