如何从对象的原型方法访问JavaScript对象属性
How to access JavaScript object properties from a prototype method of the object
我不知道如何为这个问题命名,但这是我的难题。我有一个JS对象,我已经封装并继承了方法。其中一个方法插入一个锚标记,其中onclick事件指向同一对象的一个固有方法。在第二种方法中,我遇到了麻烦,因为当用户触发锚标记的点击事件时,"this"关键字现在就是锚元素。因此,这阻止了我通过"this"关键字访问对象中的属性。这是我的简化代码,所以你可以看到我在说什么。
<!DOCTYPE html>
<html>
<head>
<title>Working out an issue</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script>
function ListContainerViewer(name, readOnly) {
this.name = name;
this.readOnly = readOnly;
}
ListContainerViewer.prototype = {
constructor: ListContainerViewer,
addListItem: function(itemId, content) {
var removeBtn = $('<a href="#"><span class="glyphicon glyphicon-remove pull-right" aria-hidden="true"></span> </a>')
.clone()
.click(this.removeListItem); // Here, "this" points to ListContainerViewer
removeBtn.appendTo($("#selectedItemList"));
},
removeListItem: function() {
if (this.readOnly == true) { // how do I point to ListContainerViewer.readOnly if this points to <a>?
event.preventDefault();
return;
} else {
this.remove(); // this should point to <a> that has the click event
}
}
}
var listContainer;
$(document).ready(function() {
listContainer = new ListContainerViewer('test', true);
$('#button').click(function() {
listContainer.addListItem('12345', 'test content');
});
});
</script>
</head>
<body>
<h1>Testing OO JS</h1>
<a id='button' href='#'>Click to add</a>
<div id="selectedItemList" style="{width: 800px; height: 400px; background-color: #dddddd}"></div>
</body>
</html>
因此,如果您运行此代码片段,单击添加链接以添加锚点标记,您会注意到,当您单击X按钮锚点时,它会触发removeListItem函数,this.readOnly不可访问,因为它指的是锚点标记。
您可以使用Function.prototype.bind
或jQuery $.proxy
方法来设置函数的this
值:
.click(this.removeListItem.bind(this));
现在,在您的函数中,this
指的是实例,而不是单击的元素。为了获得点击的元素,您可以使用event
对象的currentTarget
属性:
removeListItem: function(event) {
var element = event.currentTarget;
// ...
}
请注意,您使用的是DOM HTMLElement.remove
方法,而不是jQuery对象的remove
方法。较旧的浏览器不支持该方法。建议使用jQuery构造函数封装元素并使用它的remove
方法:$(element).remove();
相关文章:
- 如何使用此从对象访问构造函数
- LokiJS与标准Javascript对象访问
- JavaScript子对象访问自己的值
- Javascript嵌套对象访问根级别
- 即使使用 angular.fromJson() 也无法从 json 对象访问字符串
- 从表单到 Ajax 的动态对象访问
- 将 NodeJS 模块范围变量作为对象访问
- 能够从Meteor中的辅助对象访问特定值
- 从JavaScript对象访问数据's数组成员变量
- 如何从 React 中的事件对象访问自定义属性
- 函数中的对象访问;不起作用
- 如何在javascript中从JSON对象访问数组
- 如何从C#.Net Webbrowser对象访问javascript变量
- Javascript中最快的类/对象访问/实例化是什么
- 覆盖对象访问 JavaScript
- 如何从 jquery 中的另一个对象访问在一个对象中声明的变量
- 从 JavaScript 对象访问变量
- 如何从范围对象访问数据到指令
- 从vue.js中的对象访问v-repeat-overarray中的属性
- jQuery:从具有一个类的多个实例的对象访问元素