【发布时间】:2015-04-10 02:07:38
【问题描述】:
我不知道如何命名这个问题,但这是我的困境。我有一个封装和继承方法的 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>
所以如果你运行这段代码sn-p,点击add链接添加锚标签,你会注意到当你点击X按钮锚点时,它会触发removeListItem函数,this.readOnly是不可访问的,因为this是指到锚标签。
【问题讨论】:
标签: javascript oop prototype