摘要: prototype 属性使您有能力向对象添加属性和方法 constructor 属性返回对创建此对象的数组函数的引用
定义和用法
constructor 属性返回对创建此对象的数组函数的引用
语法
object.prototype.name=value
object.constructor
function Person(name){
console.log(name);
}
Person('js'); //js
为prototype对象额外添加一个constructor属性,并且该属性保存指向函数F的一个引用
var f = new F();
alert(f.constructor === F);// output true
alert(f.constructor === F.prototype.constructor);// output true
if(f.constructor === F) {
// do sth with F
}
其实constructor的出现原本就是用来进行对象类型判断的,但是constructor属性易变,不可信赖。
我们有一种更加安全可靠的判定方法:instanceof 操作符。
if(f instanceof F) {
// do sth with F
}
原型链继承,由于constructor存在于prototype对象上,因此我们可以结合constructor沿着原型链找到最原始的构造函数,如下面代码:
function Person(name){
this.name=name;
this.showMe=function(){
alert(this.name);
}
};
var one=new Person('<a href="#" class='replace_word' title="JavaScript知识库" target='_blank'>JavaScript</a>');
one.showMe(); //<a href="#" class='replace_word' title="JavaScript知识库" target='_blank'>javascript</a>
function a(c){
this.b = c;
this.d =function(){
alert(this.b);
}
}
var obj = new a('test');
console.log(typeof obj.prototype); //undefine
console.log(typeof a.prototype); //object
console.log(a.prototype);
console.log(obj.__proto__ === a.prototype) //true
上面的例子可以看出函数的prototype 属性又指向了一个对象,这个对象就是prototype对象
a.prototype 包含了2个属性,一个是constructor ,另外一个是__proto__。这个constructor 就是我们的构造函数a,那么__proto__ 是什么呢?
var obj={}; 也就是说,初始化一个对象obj。
obj.__proto__=a.prototype;
a.call(obj); 也就是说构造obj,也可以称之为初始化obj
function a(c){
this.b = c;
this.d =function(){
console.log(this.b);
}
}
a.prototype.test = function(){
console.log(this.b);
}
var obj = function (){}
obj.prototype = new a('test');
obj.prototype.test1 =function(){
console.log(22222);
}
var t = new obj('test');
t.test(); //console.log('test');
obj.prototype = p, p = new a('test'); p.__proto__ = a.prototype;
从这里可以分析得出一个结论,js中原形链的本质在于 proto
function a(c){
this.b = c;
this.d =function(){
console.log(this.b);
}
}
var obj = new a('test');
console.log(obj.constructor);//function a(){}
console.log(a.prototype.constructor);//function a(){}
根据上面讲到的__proto__ 我们来分析下,首先obj是没有constructor 这个属性的,但是 obj.__proto__ = a.prototype;就从
a.prototype中寻找,而 a.prototype.constructor 是就a,所有两者的结果是一一样的