gpt4 book ai didi

javascript - 如何避免在 javascript (ES5/ES6) 中使用 'this' 指针?

转载 作者:行者123 更新时间:2023-11-30 08:36:49 25 4
gpt4 key购买 nike

根据 Crockford 的说法,由于安全问题,最佳做法是不使用此指针。

我在 Ember guide 中找到了这个,

Person = Ember.Object.extend({
say: function(thing) {
var name = this.get('name');
alert(name + " says: " + thing);
}
});

Soldier = Person.extend({
say: function(thing) {
this._super(thing + ", sir!");
}
});

var yehuda = Soldier.create({
name: "Yehuda Katz"
});

yehuda.say("Yes"); // alerts "Yehuda Katz says: Yes, sir!"

在这种代码情况下如何避免这种情况?

最佳答案

the best practice is NOT using this pointer due to security issues.

不完全是。他的论点是你不能在不安全的环境中信任 this,因为它是由调用者决定的。这一切都是关于封装,以及您的方法只做您希望它们做的事情的安全性。使用 this 的方法可能会被欺骗去做其他事情。

考虑

function Person(name) {
this.name = name;
this.say = function(thing) {
alert(this.name+" says: "+thing);
};
}
var p = new Person("John");
p.say("this is unsafe");

有权访问 p 的恶意调用者可以这样做

p.say.call({name: "Douglas"}, "this is totally safe");

(假设他无权访问alert,并假设他不想简单地更改p.name)

一个更安全的构造函数是

function Person(name) {
return {
say: function(thing) {
alert(this.name+" says: "+thing);
}
};
}

所以当一个恶意代理通过 Person("John") 时,他只能让 John 说些什么。

How can this be avoided in such code situations?

完全没有。 Ember 拥抱 this,它确实非常有用,您应该按照框架的要求使用它。

关于javascript - 如何避免在 javascript (ES5/ES6) 中使用 'this' 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30579660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com