每个JS意见领袖都说扩展原生对象是一种不好的做法.但为什么?我们是否获得了性能?他们是否害怕有人以"错误的方式"做到这一点,并添加了可枚举的类型Object
,几乎破坏了任何对象上的所有循环?
以TJ Holowaychuk的should.js为例.他增加了一个简单的getter来Object
,一切工作正常(来源).
Object.defineProperty(Object.prototype, 'should', {
set: function(){},
get: function(){
return new Assertion(Object(this).valueOf());
},
configurable: true
});
Run Code Online (Sandbox Code Playgroud)
这真的很有道理.例如,可以扩展Array
.
Array.defineProperty(Array.prototype, "remove", {
set: function(){},
get: function(){
return removeArrayElement.bind(this);
}
});
var arr = [0, 1, 2, 3, 4];
arr.remove(3);
Run Code Online (Sandbox Code Playgroud)
是否有任何反对扩展本机类型的论据?
HTML 代码如下所示
<div id="txtarea" contenteditable="true">Some text</div>
Run Code Online (Sandbox Code Playgroud)
我必须根据上述 div 中特定位置的某个事件插入一些新文本。该事件调用函数 say updateDiv(txt, positon)。例如它说
updateDiv("more ",5);
所以div应该变成
<div id="txtarea" contenteditable="true">Some more text</div>
Run Code Online (Sandbox Code Playgroud)
我尝试了很多 javascript 和 jquery,但似乎没有任何效果。
<div contenteditable="true">
abcde<img src="abc.jp" />fg
</div>
$('div').append('<img src="abc.jpg" />'); //this will append img at end of text
Run Code Online (Sandbox Code Playgroud)
我尝试将图像添加到位置6的div中
有没有办法将图像附加到位?
$('.creditCardText').keyup(function() {
var foo = $(this).val().split("-").join(""); // remove hyphens
if (foo.length > 0) {
foo = foo.match(new RegExp('.{1,4}', 'g')).join("-");
}
$(this).val(foo);
});
Run Code Online (Sandbox Code Playgroud)
我发现这个教程将破折号每4个字符之后,从这里我的问题是什么,如果字符间隔不固定就像这个例子只每4什么如果间隔之后是3 characters "-" 2 characters "-" 4 characters "-" 3 characters "-"
这样它会出现这样的123-12-1234-123-123
.