今天我看了一篇博文,博文是关于原型对象介绍的。我把代码粘贴出来如下:
function SuperType(){}
SuperType.prototype.name = 'Sam';//在SuperType.prototype指向的对象上增加了name属性
//在SuperType.prototype指向的对象上增加了sayName方法
SuperType.prototype.sayName = function() {
document.write(this.name);
};
SuperType.prototype.setName = function(name) {
//修改这行,结果会不同
SuperType.prototype.name = name;
};
var instance1 = new SuperType();
var instance2 = new SuperType();
instance1.sayName();//Sam
instance2.sayName();//Sam
instance1.setName('Luce');
instance1.sayName();//Luce
instance2.sayName();//Luce
如果把第十行的代码改为:
this.name = name;
在进行调用出现的结果就会不同:
var instance1 = new SuperType();
var instance2 = new SuperType();
instance1.sayName();//Sam
instance2.sayName();//Sam
instance1.setName('Luce');
instance1.sayName();//Luce
输出的结果不在是Luce
instance2.sayName();//Sam
为什么??把第十行改为了this.name = name
之后输出的结果不在是Luce
而是Sam
关键问题在于this
指向的是哪里??
原型中的this
不是指的原型对象,而是调用对象。
怎样来理解这一句话???
下面来看一下一个简单的例子
function animal() {
}
animal.prototype.name = '张三';
animal.prototype.sayhello = function () {
console.log(this.name);
};
animal.prototype.setName = function (name) {
this.name = name;
};
var dog = new animal();
var cat = new animal();
dog.sayhello(); //张三
cat.sayhello(); //张三
console.log(animal.hasOwnProperty("name")); //true
dog.setName('xiaoshu');
console.log(animal.hasOwnProperty("name")); //true
dog.sayhello(); // xiaoshu
cat.sayhello(); //张三
为什么不是我想的结果???我认为1.输出的是false
,2.输出的是true
。
为什么,开始找问题在哪里??????????
console.log(animal.hasOwnProperty("name")); //true
这个是true
,照道理不应该是false
吗??
我自己把animal
看了一下,自带一个name
属性
难怪console.log(animal.hasOwnProperty("name")); //true
为true
。
修改:
那我把name
改为name1
:
function animal() {
}
animal.prototype.name1 = '张三';
animal.prototype.sayhello = function () {
console.log(this.name1);
};
animal.prototype.setName = function (name) {
this.name1 = name;
};
var dog = new animal();
var cat = new animal();
dog.sayhello(); //张三
cat.sayhello(); //张三
console.log(animal.hasOwnProperty("name1")); //false
dog.setName('xiaoshu');
console.log(animal.hasOwnProperty("name1")); //false
dog.sayhello(); // xiaoshu
cat.sayhello(); //张三
为什么还不是自己想要的结果????抓狂!!! 继续改
function animal() {
}
animal.prototype.name1 = '张三';
animal.prototype.sayhello = function () {
console.log(this.name1);
};
animal.prototype.setName = function (name) {
this.name1 = name;
};
var dog = new animal();
var cat = new animal();
dog.sayhello(); //张三
cat.sayhello(); //张三
-
console.log(dog.hasOwnProperty("name1")); //false
-
console.log(cat.hasOwnProperty("name1")); //false
dog.setName('xiaoshu');
-
console.log(dog.hasOwnProperty("name1")); //true
-
console.log(cat.hasOwnProperty("name1")); //false
dog.sayhello(); // xiaoshu
cat.sayhello(); //张三
终于看到了自己想要的结果!!!!!
dog
和cat
是调用的对象
在执行dog.setName('xiaoshu');
这句之后,setName
中的this
指向的就是dog
,dog
这个调用对象中就多了一个name1
这个属性。而这个name1
属性不在animal
函数中,只存在于dog
这个实例对象中,归dog
私自拥有,不是共享的。
这说明这个this
是指向调用对象,而不是指向原型的。