我对对象中定义的 JavaScript 方法和 this
关键字感到非常困惑。
在下面的示例中,当 Mammal
对象实例化时,会调用 toString()
方法:
function Mammal(name){
this.name=name;
this.toString = function(){
return '[Mammal "'+this.name+'"]';
}
}
var someAnimal = new Mammal('Mr. Biggles');
alert('someAnimal is '+someAnimal);
尽管事实上 toString()
方法并未在对象 someAnimal
上调用,如下所示:
alert('someAnimal is '+someAnimal.toString());
它仍然返回'someAnimal is [Mammal "Mr. Biggles"]'
。这对我来说没有意义,因为 toString()
函数没有在任何地方被调用。
然后,如果我将 toString()
方法更改为我编写的方法,例如 random()
:
function Mammal(name){
this.name=name;
this.random = function(){
return Math.floor(Math.random() * 15);
}
}
var someAnimal = new Mammal('Mr. Biggles');
alert(someAnimal);
它完全忽略 random
方法(尽管它的定义方式与 toString()
方法相同)并返回:[object对象]
我无法理解继承的另一个问题是 this
的值。例如下面的例子
function person(w,h){
width.width = w;
width.height = h;
}
function man(w,h,s) {
person.call(this, w, h);
this.sex = s;
}
this
关键字被清楚地发送到 person 对象。但是,当 person 对象接收到 this
时,它引用的是子类 man
还是父类(super class) person
呢?
感谢您消除了我对 JavaScript 中的继承和对象文字的任何困惑。
最佳答案
您在 toString
中遇到的行为方法的原因是当您进行字符串连接时,对象隐式转换为字符串(通过 ToPrimitive
内部操作,使用提示类型“String”)。
该方法调用另一个内部操作 [[DefaultValue]](hint)
.
如果提示类型是字符串,则该操作显式获取 toString
属性并调用它。
如果您的对象没有显式定义toString
方法,该方法仍然会在原型(prototype)链中更高的位置被解析,"[object Object]"
是 Object.prototype.toString 的结果方法。
例如:
var obj = {
toString:function () {
return "hello";
}
};
alert(obj + ' world');
// will alert "hello world"
现在,关于 this
值:
构造对象的方式也称为构造函数链接,即 this
value 将引用一个新对象,该对象继承自您使用 new
调用的构造函数原型(prototype)。运算符。
使用 call
调用另一个构造函数只会将所有属性分配给 this
被调用函数内的值实际上是在第一个构造函数的新对象上创建的,这并不真正影响原型(prototype)链,例如:
function Person(w,h){
this.width = w;
this.height = h;
}
function Man(w,h,s) {
Person.call(this, w, h); // will just apply the width and height assignments
this.sex = s;
}
var person = new Person(1,2);
person instanceof Person; // true
person instanceof Man; // false
var man = new Man(1,2,3);
person instanceof Person; // false
person instanceof Man; // true
编辑:为了澄清更多信息,当您调用 Person.call(this, ...);
时它只是调用该函数来对 this
的属性进行分配该函数上的值(在您的示例中为 this.width
和 this.height
),传递给作为 call
的第一个参数传递的对象,一个简化的例子:
function Test () {
this.foo = 1;
this.bar = 2;
this.baz = 3;
}
var obj = { foo: 0 }; // a simple object
Test.call(obj);
// now obj looks like this: {foo: 1, bar: 2,baz: 3}
关于javascript - 构造函数的对象字面量返回 toString() 方法,但不返回其他方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3030238/