簡體   English   中英

將函數應用於變量? 的JavaScript / jQuery的

[英]Apply a function to a variable? JavaScript/jQuery

例如

var contents = 'some text';

function fileSave(path){
// I'll handle saving the file, but I need the file contents
}

contents.fileSave('index.html');

因此,當函數對內容變量很有趣時,函數可以訪問變量。 就像replace()在JavaScript中的工作方式一樣。

EX。

str.replace();

但在這種情況下

contents.fileSave();

變量是可互換的,該函數也適用於附加的任何變量。

對不起,新手..

這可能是一種更好的方法,無需修改String.prototype

function fileEditor(path) {
    this.save = function(data) {
       // do something with path & data
    }
}

用法是,

var someFile = new fileEditor("index.html");
someFile.save("some text");

如果要向所有字符串添加方法,請將其添加到String.prototype

String.prototype.fileSave = function(path) {
    var str = this + "";
    // work with the string
    console.log(str, path);
};

只要注意你的環境。 擴展原生原型可能會與其他代碼沖突。 如果這是一個問題,你需要自己決定。

var contents = 'some text';

contents.fileSave('index.html'); // some text index.html

此代碼將函數newMethod附加到所有String實例,您也可以為其他類型執行此操作。

newMethod = function (signature) {...}
String.prototype.newMethod = newMethod
'a'.newMethod()

正如其他人所指出的,這可能不是最好的方法,但我仍然認為你理解javascript如何工作可能會很有趣(好吧,至少在javascript中開始使用原型)。

永遠不要編輯你不擁有的對象的原型! 解決方案1:使用構造函數,創建一個新對象作為丟失的源寫入解決方案2:通過對象文字聲明一個對象:

var content={
    text:"loremipsum",
    save:function(){ // do work here }
}

並通過content.save()保存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM