方法
方法不过是持有函数值的属性。 这是一个简单的方法:
let rabbit = {};rabbit.speak = function(line) {console.log(`The rabbit says '${line}'`);};rabbit.speak("I'm alive.");// → The rabbit says 'I'm alive.'
方法通常会在对象被调用时执行一些操作。将函数作为对象的方法调用时,会找到对象中对应的属性并直接调用。当函数作为方法调用时,函数体内叫做this的绑定自动指向在它上面调用的对象。
function speak(line) {console.log(`The ${this.type} rabbit says '${line}'`);}let whiteRabbit = {type: "white", speak: speak};let fatRabbit = {type: "fat", speak: speak};whiteRabbit.speak("Oh my ears and whiskers, " +"how late it's getting!");// → The white rabbit says 'Oh my ears and whiskers, how// late it's getting!'hungryRabbit.speak("I could use a carrot right now.");// → The hungry rabbit says 'I could use a carrot right now.'
你可以把this看作是以不同方式传递的额外参数。 如果你想显式传递它,你可以使用函数的call方法,它接受this值作为第一个参数,并将其它处理为看做普通参数。
speak.call(hungryRabbit, "Burp!");// → The hungry rabbit says 'Burp!'
这段代码使用了关键字this来输出正在说话的兔子的种类。我们回想一下apply和bind方法,这两个方法接受的第一个参数可以用来模拟对象中方法的调用。这两个方法会把第一个参数复制给this。
由于每个函数都有自己的this绑定,它的值依赖于它的调用方式,所以在用function关键字定义的常规函数中,不能引用外层作用域的this。
箭头函数是不同的 - 它们不绑定他们自己的this,但可以看到他们周围(定义位置)作用域的this绑定。 因此,你可以像下面的代码那样,在局部函数中引用this:
function normalize() {console.log(this.coords.map(n => n / this.length));}normalize.call({coords: [0, 2, 3], length: 5});// → [0, 0.4, 0.6]
如果我使用function关键字将参数写入map,则代码将不起作用。
