OOP编程

oop编程语言有一个标志,就是它们都有类的概念。
Js中对象定义为”无序属性的集合”,其属性可以包含基本值、对象或者函数
因此Js对象可以被想象成散列表:无非就是一组名值对,其中值可以是数据或函数。
组合使用构造函数和原型模式,是目前Js使用最广泛、认同度最高的一种创建自定义类型的方法
构造函数模式(浪费内存)

instanceOf      测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性
(用法:object instanceof constructor)

原型链模式

isPrototypeOf           测试一个对象是否存在于另一个对象的原型链上
(Object.prototype.isPrototypeOf())
hasOwnProperty          判断某个对象是否含有指定的属性(object.hasOwnProperty(prop))
in                      判断指定的属性是否存在于指定的对象中
(prop in object)
举例说明:
function Person(){}
Person.prototype.name = 'a';
Person.prototype.age = 20;
Person.prototype.sayName = function(){ return this.name};

var person1 = new Person();
var person2 = new Person();
----------
//isPrototypeOf
console.log(Person.prototype.isPrototypeOf(person1));//true
----------


//hasOwnProperty
console.log(person1.hasOwnProperty('name'));//false
person1.name = "bbbb";
console.log(person1.hasOwnProperty('name'));//true
----------


//in
console.log("name" in person1);//true
console.log("name" in person2);//false

猜你喜欢

转载自blog.csdn.net/eatgirlhui_unique/article/details/56843287
OOP
今日推荐