javascript的原型

来源:互联网 发布:ggplot2 python 编辑:程序博客网 时间:2024/04/27 09:27

显示的原型prototype

自定义函数具有prototype属性

例如

function A(){    console.log("A");}var B = function(){    console.log("B");}var C = new Function("console.log('C')");A.prototype   //Object {}B.prototype   //Object {}C.prototype   //Object {}var a1 = new A();var b1 = new B();var c1 = new C();a1.prototype  //undefinedb1.prototype  //undefinedc1.prototype  //undefined

在通过new构造函数的过程中
发生了什么呢?以实例化a1为例

var obj = {};obj.__proto__ = A.prototype;A.call(obj);return obj;

最终返回的是一个对象obj,这个obj赋值给了a1

typeof A;//"function"typeof a1;//"object"

特例:
通过Function.prototype.bind方法构造出来的函数是个例外,它没有prototype属性

NOTE Function objects created using Function.prototype.bind do not
have a prototype property or the [[Code]], [[FormalParameters]], and
[[Scope]] internal properties. —– ECMAScript Language Specification

示例代码:

var d = 1;var D = {    d : 0}var e = function(){    console.log(this.d);}var f = e.bind(D);e();//1f();//0

这个时候f也是一个函数

typeof e;  //"function"typeof f;  //"function"e.prototype; //Object {}f.prototype; //undefined

javascript内置函数的prototype

Array.__proto__ === Function.prototype;Date.__proto__ === Function.prototype;...Function.__proto__ === Function.prototype;Object.__proto__ === Function.prototype;//特殊的内置对象Math.__proto__ === Object.prototype;JSON.__proto__ === Object.prototype;

隐示的原型proto([[proto]])

在javascript中对象都具有proto属性

var a = function(){}var b = 1;var c = "string";var d = false;var e = null;var f = undefined;//除了对象外对五种基本的数据类型分别取__proto__//b.__proto__  --> Number {[[PrimitiveValue]]: 0}//c.__proto__  --> String {length: 0, [[PrimitiveValue]]: ""}//d.__proto__  --> Boolean {[[PrimitiveValue]]: false}//e.__proto__  -->Uncaught TypeError: Cannot read property '__proto__' of null(…)//f.__proto__  -->Uncaught TypeError: Cannot read property '__proto__' of undefined(…)//数据类型是null和undefined的会报错,虽然typeof null === "object",但是这是javascript引擎本身的一个错误

隐示的原型proto指向构造该实例对象的构造函数的原型对象

function A(){}var a = new A();a.__proto__ === A.prototype;

其中a是构造函数A的一个实例,a的隐示的原型指向构造函数的原型对象(A.prototype)

如何实现继承和原型链

function A(){}function B(){}A.prototype.println(){    console.log("A");}B.prototype = new A();var b1 = new B();//b1.__proto__ === B.prototype//B.prototype.__proto__ === A.prototype//A.prototype.__proto__ === Object.prototype//Object.prototype.__proto__ === null

上面就是我们时常说的原型链,原型链的实现依靠 proto 和 prototype
依靠 proto 和 prototype我们也实现了B对A的继承,将A的一个实例赋给B的prototyep属性,B.prototype.proto –> A.prototype。这里继承是指继承的A上prototype对象

0 0