javascript之面向对象学习笔记02

Object 原型中的常用方法

1、constructor

语法:构造函数.prototype.constructor,

作用:指向构造函数本身

function Person(){}

console.log( Person === Person.prototype.constructor );//true

  

 

2、hasOwnProperty

语法:对象.hasOwnProperty( 属性名字 )

作用:检测属性为对象原生提供还是继承所得

function Person () {}

Person.prototype.name = "landmine";

var p = new Person();

p.age = 18;

console.log(p.hasOwnProperty("name")); //false

console.log(p.hasOwnProperty("age")); //true

  

 

3、isPrototypeOf

语法:对象1.isPrototypeOf( 对象2 )

作用:判断对象1是否为对象2的原形对象

function Person () {}

var p = new Person();

console.log( Person.prototype.isPrototypeOf(p) );//true

  

 

4、propertyIsEnumerable

语法:对象.propertyIsEnumberable( 属性名字 )

作用:原生属性是否可以枚举, 原生属性是否可以被 for-in 遍历到,不可枚举或不存在该属性或者不是原生属性则返回false

function Person () {

this.age = 18

}

var p = new Person();

p.name = "landmine";

console.log(p.propertyIsEnumerable( "name" )); //true

console.log(p.propertyIsEnumerable( "age" ));//false

console.log(p.propertyIsEnumerable( "gender" ));//false

  

 

 

原型链

1、对象都有原型对象, 对象默认继承自原型对象

2、 函数被定义后, 默认就有原型属性, 原型属性也是对象

3、函数的原型属性默认继承自 Object.prototype

4、原型对象中 constructor 指向对应的构造函数

5、 所有的函数都是 Function 的实例

6、 函数也是对象,所有函数的属性默认继承自Function.Prototype

7、Function本身也是函数。即Function.__prototype === Function.Prototype

 

基本的概念

prototype 是函数的原型属性, 是该函数创建的对象的原型对象

__proto__ 是对象的原型对象, 是创建该对象的构造函数的 原型属性

 

 

原型链图

 

 

instanceof运算符

语法:对象  instanceof 构造函数

作用:判断构造函数是否在对象的原形链上

 

function Foo() {}

function Fn() {}

var f1 = new Fn();

console.log( f1 instanceof Fn )//true

console.log( f1 instanceof Object )//true

console.log( f1 instanceof Foo )//false

Fn.prototype = new Foo();//修改函数的原形链

var f2 = new Fn();

console.log( f1 instanceof Foo )//false

console.log( f2 instanceof Foo )//true

  

 

Fn原形属性被更改至Foo后,Foo就在重新声明的f2的原型链上,而f1的原型链并没有更改,Foo并没有在f1的原型链上。

修改原型链也可以直接修改对象的__proto__属性,在上面代码的基础上添加如下代码后,Foo也存在f1的原型链上。

F1.__proto__ = new Foo();

console.log( f1 instanceof Foo ) // true

 

 

new Function创建函数

语法: var 函数名 = new Function( arg1, arg2, arg3, ..., argN, body );

作用:创建函数,参数列表中最后一个位函数的内容,其他为函数的参数。

var fnMax = new Function( 'a', 'b', 'return a > b ? a : b;' );

var res = fnMax( 1, 2 );

console.log(res); // 2

  

posted @ 2016-04-02 13:17  地雷  阅读(122)  评论(0编辑  收藏  举报